我正在尝试通过WinSock2发送HTTP请求。我终于做到了,但是,当我关闭连接的发送一半时,我无法弄清楚连接将被关闭的原因。
当客户端或服务器希望超时时,应该在传输连接上发出正常关闭。客户和服务器应该经常关注运输关闭的另一侧,并在适当的时候做出响应。
服务器不应在传输响应的过程中关闭连接,除非怀疑网络或客户端故障。
我认为套接字仍然会收到消息,直到服务器无法发送任何消息,但服务器只是关闭连接意外。
C:\Users\970067a\Desktop>gcc test.c -lWs2_32 && a
Bytes Sent: 59
Bytes received: 787
Bytes received: 222
Connection closed
C:\Users\970067a\Desktop>gcc test.c -lWs2_32 -D SHUTDOWN_SD_SEND && a
Bytes Sent: 59
Connection closed
以下是我的源代码的一部分:
...
iResult = getaddrinfo("www.google.com", "http", &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
...
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "GET / HTTP/1.1\r\nhost: www.google.com\r\nConnection: close\r\n\r\n";
char recvbuf[DEFAULT_BUFLEN];
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection for sending since no more data will be sent
// the client can still use the ConnectSocket for receiving data
#ifdef SHUTDOWN_SD_SEND
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
#endif
// Receive data until the server closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
...
答案 0 :(得分:0)
RFC 2616中没有关于半关闭或关闭的内容。你不应该用HTTP来做它们。