How can you check if a network socket (System.Net.Sockets.Socket) is still connected if the other host doesn't send you a packet when it disconnects (e.g. because it disconnected ungracefully)?
In TCP there is only one way to detect an orderly disconnect, and that is by getting zero as a return value from read()/recv()/recvXXX() when reading. There is also only one reliable way to detect a broken connection: by writing to it.
There is an easy way to check socket connection state via poll call. First, you need to poll socket, whether it has POLLIN event. If socket is not closed and there is data to read then read will return more than zero. If socket is closed then POLLIN flag will be set to one and read will return 0.
isConnected() tells you whether you have connected this socket. You have, so it returns true. isClosed() tells you whether you have closed this socket. Until you have, it returns false.
The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket. send() and if it returns 0 you can no longer send data on that socket.
As Paul Turner answered Socket.Connected
cannot be used in this situation. You need to poll connection every time to see if connection is still active. This is code I used:
bool SocketConnected(Socket s) { bool part1 = s.Poll(1000, SelectMode.SelectRead); bool part2 = (s.Available == 0); if (part1 && part2) return false; else return true; }
It works like this:
s.Poll
returns true if s.Available
returns number of bytes available for readingAs zendar wrote, it is nice to use the Socket.Poll
and Socket.Available
, but you need to take into consideration that the socket might not have been initialized in the first place. This is the last (I believe) piece of information and it is supplied by the Socket.Connected
property. The revised version of the method would looks something like this:
static bool IsSocketConnected(Socket s) { return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected); /* The long, but simpler-to-understand version: bool part1 = s.Poll(1000, SelectMode.SelectRead); bool part2 = (s.Available == 0); if ((part1 && part2 ) || !s.Connected) return false; else return true; */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With