c ++ recv函数很慢

时间:2017-12-05 12:19:33

标签: c++ windows sockets http-post

我有一个程序,需要通过HTTP POST请求与服务器通信,然后从服务器接收答案。发送和接收代码处于循环中,应尽快执行。我的问题是,recv() - 函数需要大约500毫秒才能完成。我得到的答案的长度是未知的。

if (send(m_socket, buffer, strlen(buffer), 0) != strlen(buffer))
{
    cout << "HTTP: Error sending:" << WSAGetLastError() << endl;
    return "0";
}
const int buflen = 322;
char buffer2[buflen];   

recv(m_socket, buffer2, buflen, 0);

我可以改变什么来将recv() - 函数的时间减少到几毫秒?

这是完整的代码:

WSADATA wsaData;
SOCKET m_socket;

int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (iResult)
    cout << "Error" << endl;

m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (m_socket == INVALID_SOCKET)
    cout << "Invalid Socket : " << WSAGetLastError() <<endl;

setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, "1", 1);

sockaddr_in clientService;
clientService.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &clientService.sin_addr.s_addr);
clientService.sin_port = htons(80);

if (connect(m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR)
{
    cout << "Connection Failure"<<WSAGetLastError()<<endl;
    WSACleanup();
    return 0;
}
while(alpha)
{
    if (send(m_socket, buffer, strlen(buffer), 0) != strlen(buffer))
    {
        cout << "HTTP: Error sending:" << WSAGetLastError() << endl;
        return "0";
    }
    const int lang = 322;

    char buffer2[lang]; 

    recv(m_socket, buffer2, lang, 0);
    cout<<buffer2<<endl;
}

0 个答案:

没有答案