Been trying some different ways of detecting if a remote Socket has disconnected.
I currently do this to check if a socket is connected.
public void CheckSocket()
{
try
{
bool test1 = s.Poll(_MicrosecondFaultTolerance, SelectMode.SelectRead);
bool test2 = (s.Available == 0);
if (test1 && test2)
_Active = false;
}
catch
{
_Active = false;
}
}
This for some reason works perfectly on the first drop every time no questions asked but after that the check does not set _Active to false and thus the client is never considered “disconnected”. Are there any other ways i could test a Connection or have a more reliable result at all.
I’m not sure what you mean by “the first drop”, since once the connection under a socket has been dropped, the socket must be closed. That all depends on what you are doing outside of the
CheckSocket()function. But assuming that’s all handled correctly, simply polling the socket will not work reliably if the underlying connection is idle.A disconnect can only be detected if there is some traffic on the underlying transport. If a connection is abandoned (not closed) while idle, it will quietly sit there forever. To detect an abandoned connection while idle, use
setsockopt()withSO_KEEPALIVE. TCP will periodically exchange dummy traffic with the other side to test whether the connection is still alive and prevent any NAT or other dynamic routing rules from timing out. Note that it still may take 30 seconds or more to detect a drop, as that is TCP’s default timeout.