-
closesocket()
I see different examples.
Do I need to close both sockets or only the first one if I dont need them anymore?
Code:
if ((sock2 = accept(Sock1, (struct sockaddr *)&ClientAddr, &paddr_sz)) == INVALID_SOCKET)
{
printf("Accept error = %d", WSAGetLastError());
closesocket(Sock1);
return 1;
}
...
//Close the socket cleanly
closesocket(sock2);
closesocket(Sock1);
-
Re: closesocket()
You only have to close the client socket after you send and recv your data.
You also want to follow MSDNs preferred method for shutting down communications.
At minimum:
Code:
//accept() here
//Recv Client Data
//Send back response to client
//Graceful shutdown
shutdown(sock2, SD_SEND)
//Close the socket cleanly
closesocket(sock2);
With More Debugging:
Code:
if (shutdown(clientSocket, SD_SEND) == SOCKET_ERROR)
{
OutputDebugString("shutdown() Error");
}
if (closesocket(clientSocket) == SOCKET_ERROR)
{
OutputDebugString("closesocket() Error");
}
-
Re: closesocket()
Thank you.
Its the first time i hear about the shutdown(). Not many people use this function.
-
Re: closesocket()
Sure, also you don't shut down the server socket, only the client socket. The server socket stays open to handle future communications. The accept() function will actually take the socket connection from the Server Socket and move it over to the client socket. The server socket acts like a post office, rerouting your mail to your mailbox (like the client socket), so closing it would impede future communications.
HTH,
-
Re: closesocket()
-
Re: closesocket()
Thanks man, appreciate the help!
-
Re: closesocket()
The MSDN link you gave me talking about the client
"Gets FD_READ and calls recv to get any response data sent by server ."
FD_READ is a windows message. Im only using a console program.
Do you still need to use shutdown(clientSocket, SD_SEND) in a console application?
-
Re: closesocket()
Yes. Keep in mind it is still a Windows Console!;)