我正在尝试制作一个在winsock中使用HTTP的程序,但我遇到了一个问题,其中recv函数只是挂在那里。
int connect()
{
WSADATA t_wsa; //WSADATA structure
WORD wVers = 0x0202; //version number
int iError; //error number
wVers = MAKEWORD(2, 2); // Set the version number to 2.2
iError = WSAStartup(wVers, &t_wsa); // Start the WSADATA
if(iError != NO_ERROR || iError == 1)
{
printf("Error at WSAStartup()\n");
WSACleanup();
system("PAUSE");
return 1;
}
/* Correct version? */
if(LOBYTE(t_wsa.wVersion) != 2 || HIBYTE(t_wsa.wVersion) != 2)
{
printf("Incorrect version\n");
WSACleanup();
system("PAUSE");
return 1;
}
SOCKET sClient;
sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sClient == INVALID_SOCKET || iError == 1)
{
printf("Invalid Socket!\n");
WSACleanup();
system("PAUSE");
return 1;
}
SOCKADDR_IN sinClient;
memset(&sinClient, 0, sizeof(sinClient));
char cIP[50];
strcpy_s(cIP, "98.139.183.24");
sinClient.sin_family = AF_INET;
sinClient.sin_addr.s_addr = inet_addr(cIP); // Where to start server
sinClient.sin_port = htons(80); //Port
if(connect(sClient, (LPSOCKADDR)&sinClient, sizeof(sinClient)) == SOCKET_ERROR)
{
/* failed at starting server */
printf("Could not connect ot the server!\n");
WSACleanup();
system("PAUSE");
return 1;
}
// Now we can send/recv data!
printf("YOU ARE CONNECTED!\r\n");
string buffer;
buffer += "GET / HTTP/1.1\r\n";
buffer += "Host: http://www.yahoo.com/\r\n";
buffer += "Connection: close\r\n\r\n";
const char *cha = buffer.c_str();
int sent;
int response;
sent = send(sClient, cha, sizeof(cha) - 1, 0);
char recvbuf[50000];
response = recv(sClient, recvbuf, 50000, 0);
recvbuf[response] = '\0';
printf("\nReceived data = %s", recvbuf);
WSACleanup();
return(0);
}
“发送”将在发送功能后打印,但在recv打印后没有任何内容。
我在这里缺少什么?
答案 0 :(得分:4)
可能的原因是send()
未发送预期数据:
sent = send(sClient, cha, sizeof(cha) - 1, 0);
sizeof(cha) - 1
实际上是sizeof(char*) - 1
,而不是数据的实际长度:请改用buffer.length()
。
请注意,您可以在单个语句中使用字符串文字构造std::string
,而不是通过多个连接构造它。但是,由于std::string
仅用于获取const char*
,因此根本没有理由使用std::string
:
const char* buffer = "GET / HTTP/1.1\r\n"
"Host: http://www.yahoo.com/\r\n"
"Connection: close\r\n\r\n";
sent = send(sClient, buffer, strlen(buffer), 0);
检查send()
和recv()
的返回值以确定成功或失败,尤其是recv()
,因为结果用于索引数组。如果失败,recv()
会返回SOCKET_ERROR
,我认为这是-1
。
正确处理HTTP响应需要付出巨大努力。接收代码需要检查返回的HTTP headers以确定如何处理响应内容。例如,HTTP响应可以被分块或不分块。存在用于管理HTTP请求的库,一个是cpp-netlib(大约在2013年2月isocpp.org宣布)。