1

我正在尝试在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);
}

“sent”将在发送功能后打印,但在 recv 打印后什么也没有。

我在这里想念什么?

4

1 回答 1

4

一个可能的原因是send()没有发送预期的数据:

sent = send(sClient, cha, sizeof(cha) - 1, 0);

sizeof(cha) - 1实际上是,sizeof(char*) - 1而不是数据的实际长度:buffer.length()改为使用。

请注意,您可以std::string在单个语句中构造字符串文字,而不是通过多个连接来构造它。但是,由于std::string用于获取 a const char*only,因此根本没有理由使用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 标头以确定如何处理响应内容。例如,HTTP 响应可能被分块或不分块。存在用于管理 HTTP 请求的库,其中一个是cpp-netlib(大约 2013 年 2 月在isocpp.org上宣布)。

于 2013-04-03T14:45:50.953 回答