I'm trying to write a very simple TCP server in .NET, that deals with just one connection for one client, and my challenge is detecting a half-open connection.
As per this ubiquitous MSDN code...
// This is how you can determine whether a socket is still connected.
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;
}
... I thought the intent of this was to uncover any real-world connection issue (such as the remote client's network cable being unplugged) and throw the desired exception.
Yet, I also understand that issuing a Send() simply causes the data to be put into the socket's underlying send buffer... so obviously it would not fail simply because of a problem on the client's side.
I've read that you need to do a follow-up Receive() to actually get the results of the zero-length send test. However, my server is currently using a continual BeginReceive approach, where, as soon as I actually receive data and process it, I start a BeginSend() and then issue another BeginReceive().
In other words, at the time that the "MSDN test" is performed, I already have a pending receive in effect. Wouldn't that somehow sense the lack of ACK and signal the error?
Thanks
Software wise the way to prove a connection is still alive, is to send a message to the other end and then wait until timeout for a response. It's not just that the connection is set up, but that the other end is responding usually.
Not really any different to the way a physical connection would be proven send 5v down one pair, see if about 5v comes back on the other.
Google TCP/IP Heartbeat for more help.