Text和Bin Buffer如何设置WSABUF.buf?

How Do I Set WSABUF.buf For Text And Bin Buffer?

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

不知何故,WSASend() 更喜欢让 WSABUF.buf 指向一个 std::vector 以使其适用于图像文件(.jpg、.png 等)。

在测试期间,image/* mimetypes return 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 sits in a repository.

尝试更像这样的东西:

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));
}