For non-blocking sockets, I know that recv() will return 0 with no error code if the remote client has gracefully disconnected (assume we are the server). How would you detect abnormal disconnection? Will recv() still return 0, or is there some other way to use the API to detect this?
For non-blocking sockets, I know that recv() will return 0 with no error code
Share
If connection is physically broken or the other host has shut down without gracefully closing the socket your
recvwill be waiting forever. At the socket level, you can useselect()and set timeout for waiting data to be available for reading on the socket. You’ll have this in a loop and if data is available – read it (recv()); ifselect()times out, close the socket gracefully and reconnect.Another solution would be having implemented keep-alives in your protocol. One side is periodically sending keep-alive messages and another side has a timer with a timeout set (adjusted to sending period) and is waiting for them. If timer times out, “waiting” host closes its socket and tries to reconnect.