First off, I know there are other solutions and practices but I'm referring to MS proposed code from .NET documentation.
It goes like this:
client.Connect(anEndPoint);
bool blockingState = client.Blocking;
try
{
byte [] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
Console.WriteLine("Connected!");
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
Console.WriteLine("Still Connected, but the Send would block");
else
{
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
}
finally
{
client.Blocking = blockingState;
}
Console.WriteLine("Connected: {0}", client.Connected);
I've tried using it in my TCP client to detect disconnection from server. My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.
I'm asking anyone who tried using this method to share experiences and maybe help make it more robust.