如何为文本和Bin缓冲区设置WSABUF.buf?

时间:2015-04-23 01:36:30

标签: c++ http winsock memcpy

我正在重构代码以不使用std :: vector< byte>。我该如何做到这一点?

不知何故,WSASend()更喜欢让WSABUF.buf指向std :: vector< byte>它适用于图像文件(.jpg,.png等)。

在测试期间,image / * mimetypes返回net :: ERR_CONTENT_LENGTH_MISMATCH。

byte* HttpResponse::GetResponse2(ULONG *len)
{
    DWORD dwThreadId = GetCurrentThreadId();
    char *buffer = (char*)malloc(DATA_BUFSIZE);
    memset(buffer, 0, DATA_BUFSIZE);

    std::vector<byte> binbuffer = m_sbResponse;

    std::string ctstr;
    ctstr.assign(contenType.begin(), contenType.end());
    size_t siz = binbuffer.size();
    std::string ssiz = std::to_string(siz);

    strcpy_s(buffer, DATA_BUFSIZE, resp_ok);
    strcat_s(buffer, DATA_BUFSIZE, "\n");
    strcat_s(buffer, DATA_BUFSIZE, "Date: ");
    strcat_s(buffer, DATA_BUFSIZE, "May 10, 2015");
    strcat_s(buffer, DATA_BUFSIZE, "\n");
    strcat_s(buffer, DATA_BUFSIZE, "Content-Type: ");
    strcat_s(buffer, DATA_BUFSIZE, ctstr.c_str());
    strcat_s(buffer, DATA_BUFSIZE, "\n");
    strcat_s(buffer, DATA_BUFSIZE, "Content-Length: ");
    strcat_s(buffer, DATA_BUFSIZE, ssiz.c_str());
    strcat_s(buffer, DATA_BUFSIZE, "\n");
    strcat_s(buffer, DATA_BUFSIZE, "\n");

    int bufsiz = strlen(buffer) + binbuffer.size() + 1;
    byte* buffer2 = (byte*)malloc(bufsiz);
    memset(buffer2, 0, bufsiz);
    strcpy_s((char*)buffer2, strlen(buffer)+1, buffer);
    int n = strlen((char*)buffer2);

    std::vector<byte>::iterator it;
    for (it = binbuffer.begin(); it != binbuffer.end(); it++)
    {
        byte b = *it;
        buffer2[n++] = b;
    }

    *len = strlen((char*)buffer2);

    return buffer2;
}

我需要为WSA *设置一个属性来处理我正在尝试做的事情吗?

file位于repository

1 个答案:

答案 0 :(得分:1)

尝试更像这样的东西:

byte* HttpResponse::GetResponse2(ULONG *len)
{
    *len = 0;

    std::ostringstream oss;            
    oss << resp_ok << "\n"
    oss << "Date: " << "May 10, 2015" << "\n";
    oss << "Content-Type: " << contenType << "\n";
    oss << "Content-Length: " << m_sbResponse.size() << "\n";
    oss << "\n";

    std::string s = oss.str();

    int bufsiz = s.length() + m_sbResponse.size();
    byte* buffer2 = (byte*) malloc(bufsiz);
    if (buffer2)
    {
        std::copy(s.begin(), s.end(), buffer2);
        std::copy(m_sbResponse.begin(), m_sbResponse.end(), &buffer2[s.length()]);
        *len = bufsiz;
    }

    return buffer2;
}

话虽如此,我强烈建议不要退回byte*。您的GetResponse()方法将输出std::vector<byte>作为参数,您应该坚持使用该模型:

void HttpResponse::GetResponse2(std::vector<byte> *pv)
{
    pv->clear();

    std::ostringstream oss;            
    oss << resp_ok << "\n"
    oss << "Date: " << "May 10, 2015" << "\n";
    oss << "Content-Type: " << contenType << "\n";
    oss << "Content-Length: " << m_sbResponse.size() << "\n";
    oss << "\n";

    std::string s = oss.str();

    pv->reserve(s.length() + m_sbResponse.size());
    std::copy(s.begin(), s.end(), std::back_inserter(*pv));
    std::copy(m_sbResponse.begin(), m_sbResponse.end(), std::back_inserter(*pv));
}