how to detect connection lost with async sockets
how can I know when the server disconnects me or the connection is lost in other situations when using async sockets?
If you are in a non-windows environment (which you should be
), you may want to try the following.
Note:
The function recv() will return 0 (zero) if the socket has disconnected.
So does send().
![](wink.gif)
Note:
The function recv() will return 0 (zero) if the socket has disconnected.
So does send().
fd_set mySet;SOCKET theConnectedSocket;TIMEVAL tv;// ( ... in main loop where you recv data or whatnot ... )// Set up our fd_set structureFD_ZERO(&mySet);// Add our ConnectedSocket to the sockets that mySet contains.FD_SET(theConnectedSocket, &mySet);// Wait only 0.025 seconds for the select() function to returntv.tv_sec = 0;tv.tv_usec = 25;// Call selectselect(FD_SETSIZE, &mySet, NULL, NULL, &tv);// Check to see if the socket is readable OR has disconnectedif( FD_ISSET( theConnectedSocket, &mySet ) ){ // Try to read data int iReturn = recv(theConnectedSocket, theBuffer, BufferSize); // If iReturn == zero, then the socket disconnected if( iReturn == 0 ) { closesocket(theConnectedSOcket); // And whatever else you have to do. }}
I would prefer using the send() method and sending 0 bytes.
Because what happens, when you''re recv()''ing and there is really no data pending? you get a zero as return value.
The MSVC++ Help says:
yesa thats it. If your connection is gracefully closed you will probably get a close message or something from your server app.
WSACONNRESET is the other case...
Because what happens, when you''re recv()''ing and there is really no data pending? you get a zero as return value.
The MSVC++ Help says:
quote:
...
Calling send with a zero len parameter is permissible and will be treated by implementations as successful. In such cases, send will return zero as a valid value.
..
quote:
...
If no error occurs, send returns the total number of bytes sent, which can be less than the number indicated by len for nonblocking sockets. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
...
quote:
...
WSAECONNRESET
The virtual circuit was reset by the remote side executing a "hard" or "abortive" close. For UPD sockets, the remote host was unable to deliver a previously sent UDP datagram and responded with a "Port Unreachable" ICMP packet. The application should close the socket as it is no longer usable.
yesa thats it. If your connection is gracefully closed you will probably get a close message or something from your server app.
WSACONNRESET is the other case...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement