int make_server_socket(int port, string host)
{
WSADATA inet_WsaData;
WSAStartup(MAKEWORD(2, 0), &inet_WsaData);
if (LOBYTE(inet_WsaData.wVersion) != 2 || HIBYTE(inet_WsaData.wVersion) != 0)
{
WSACleanup();
return -1;
}
int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
struct hostent * hp = ::gethostbyname(host.c_str());
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
memcpy(&saddr.sin_addr, hp->h_addr, 4);
if (connect(tcp_socket, (const struct sockaddr *)&saddr, sizeof(saddr)) == -1)
{
cerr << "error in connect" << endl;
}
return tcp_socket;
}
int main()
{
string url = "www.baidu.com";
string name = "/";
int client_socket = make_server_socket(80, url);
string request = "GET " + name + " HTTP/1.1\r\nHost:" + url + "\r\nConnection:Keep-alive\r\n\r\n";
string request2 = "GET " + name + " HTTP/1.1\r\nHost:" + url + "\r\nConnection:Close\r\n\r\n";
if (send(client_socket, request.c_str(), request.size(), 0) == SOCKET_ERROR)
{
cout << "send error" << endl;
}
char buf[1024];
::memset(buf, 0, sizeof(buf));
int n = 0;
while ((n = recv(client_socket, buf, sizeof(buf)-sizeof(char), 0)) > 0)
{
}
closesocket(client_socket);
system("pause");
return 0;
}
当我用request时(connection:keep-alive)花费的时间比用request2(connection:close)要长
Because the socket you are using is blocking, the condition of the while loop is that the return value of recv is greater than 0.
When the situation is connection: keep-alive
The last recv has data, and the return value is greater than 0.
According to the logic of your code, after the last recv, recv will be executed again. At this time, it is blocked and will not return immediately. It will not return until the default timeout of the socket.
When the situation is connection:close
After the last recv, the server's TCP connection will be closed, and executing recv again will return 0 immediately, so it will not take long.
How do you calculate the length of time?