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)要长
阿神2017-04-17 11:19:07
因為你使用的套接字是阻塞的,while迴圈的條件是,recv的回傳值大於0。
當情況為connection:keep-alive
最後一次recv是有資料的,回傳值是大於0的。
依照你程式碼的邏輯,最後一次recv之後,還會再執行一直recv,這時候阻塞了,不會立刻回,直到套接字預設的逾時時間才會回傳。
當情況為connection:close
最後一次recv之後,伺服器的TCP連線會關閉,再執行一次recv會立刻回傳0,所以時間不會長。