c++ - 为什么当客户端只关闭发送一半的连接时,HTTP 服务器就关闭连接?

标签 c++ c windows http network-programming

Possible Duplicate:
Winsock recv not working after shutdown

我正在尝试通过 WinSock2 发送 HTTP 请求。我终于做到了,但是,我不明白为什么当我关闭连接的发送一半时连接会被关闭。

根据RFC2616 sec8.1.4 :

When a client or server wishes to time-out it SHOULD issue a graceful close on the transport connection. Clients and servers SHOULD both constantly watch for the other side of the transport close, and respond to it as appropriate.

Servers SHOULD NOT close a connection in the middle of transmitting a response, unless a network or client failure is suspected.

我认为套接字仍会接收消息,直到服务器没有任何内容可发送,但服务器只是意外关闭连接。

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

...

最佳答案

RFC 2616 中没有任何关于半关闭或关闭的内容。您不应该使用 HTTP 来执行这些操作。

关于c++ - 为什么当客户端只关闭发送一半的连接时,HTTP 服务器就关闭连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150910/

相关文章:

c - 在 C 中使用 fopen 进行迭代

windows - 如何定义安装后出现在开始菜单上的快捷方式?

javascript - 桌面通知中的自定义/样式标题和正文方向(chrome)

我可以获得内存中已有数据支持的 FILE* 吗?

c++ - 卸载注入(inject)的 DLL

c++ - setuid 和 getuid 似乎不起作用

c - SQLite3 存储不可读的文本

c - 如何在c中分配结构体数组?

c++ - 将调用哪个重载版本的运算符

c++ - COM 服务器的奇怪行为