Rumah > Soal Jawab > teks badan
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,所以时间不会长。