0

可能重复:
Winsock recv 关机后不工作

我正在尝试通过 WinSock2 发送 HTTP 请求。我终于做到了,但是,当我关闭连接的发送一半时,我无法弄清楚为什么连接会关闭。

根据RFC2616 sec8.1.4

当客户端或服务器希望超时时,它应该在传输连接上发出正常关闭。客户端和服务器都应该不断地观察传输关闭的另一端,并在适当的时候做出响应。

服务器不应该在传输响应的过程中关闭连接,除非怀疑网络或客户端故障。

我想套接字仍然会接收消息,直到服务器没有要发送的内容,但服务器只是意外关闭了连接。

alt

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();

...
4

1 回答 1

0

RFC 2616 中没有关于半关闭或关闭的内容。你不应该用 HTTP 来做这些事情。

于 2012-10-31T09:44:06.287 回答