If my client's connection is broken on the other end( kill -9 server)
. It takes several minutes for the client to determine that something is wrong. Socket.Connected
returns true even though connection is actually broken.
What is the fastest way to determine that the connection doesn't exist, once the other end breaks the link?
Client code:
try{
Socket socket= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
/*Assume there is a connection on the other end*/
while (socket.Connected)
{
/*Do some processing*/
}
}catch (SocketException se){
Console.WriteLine(ex.Message);
} catch (Exception ex){
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("something bad happen");
}
I refer you to my answer to your C++ version of this question...
Try checking the
Available
property, it should throw aSocketException
when the connection has been closed.Source
Edit, here is how you would use it:
You could also try using the
Poll
method.From Source:
Have you tried to set a shorter connection timeout ?
Maybe the
SendTimeout
and/orReadTimeout
properties of theSocket
could help?Spawn another thread that is constantly pinging the server - really the best you can do since a socket is not an active connection.
This seems to work for me... Does anyone see any issues?
Can also be put into an extension method.
Now you can easily use it in your code dealing with sockets.