Possible Duplicate:
Winsock recv not working after shutdown
I am trying to send HTTP request via WinSock2. I finally did it, however, I can't figure out why the connection will be closed when I shutdown the send half of the connection.
According to 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.
I suppose the socket will still receive messages untill the server has nothing to send, but the server just close the connection unexpectedly.
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
Below is part of my source code:
...
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();
...