刚才抓一个网页,发送如下请求
GET /xxx.xxx HTTP/1.1
Host: xxx
然后这样接收对方返回的数据:
string strRecv = "";
char* temp = new char[2048];
int rc = recv(conn, temp,2048, 0);
strRecv += temp;
cout << temp << endl;
ZeroMemory(temp,2048);
while (rc > 0)
{
if (rc == SOCKET_ERROR)
{
break;
}
rc = recv(conn, temp, 2048, 0);
//strRecv += temp;
cout << temp << endl;
ZeroMemory(temp,2048);
}
char* temp = new char[2048];
int rc = recv(conn, temp,2048, 0);
strRecv += temp;
cout << temp << endl;
ZeroMemory(temp,2048);
while (rc > 0)
{
if (rc == SOCKET_ERROR)
{
break;
}
rc = recv(conn, temp, 2048, 0);
//strRecv += temp;
cout << temp << endl;
ZeroMemory(temp,2048);
}
追踪执行后发现recv该页面所有数据后最后一次进入recv并没有返回0,而是阻塞住了,因为对方迟迟不关闭connection连接,后来想了想,http协议在请求数据的时候可以设置connection:close,加上后果然好了,以后请求数据要记住这样写:
GET /xxx.xxx HTTP/1.1
Host: xxx
Connection: Close
只有加入这最后一行,对方发送完数据才会关闭连接,只有对方关闭连接,我们这边才能recv到一个0,从而根据recv返回的0判断接收数据完毕,然后我们就可以退出拼接数据包的循环。