Sasha
Sasha

Reputation:

How can I tell if the connection has been broken in my sockets based client?

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");
 }

Upvotes: 8

Views: 4619

Answers (6)

Len Holgate
Len Holgate

Reputation: 21616

I refer you to my answer to your C++ version of this question...

Upvotes: 0

Sasha
Sasha

Reputation:

This seems to work for me... Does anyone see any issues?

public bool IsConnected
{
         get {return !(Socket.Poll(1, SelectMode.SelectRead) 
                                  && m_socket.Available ==0)}
}

Can also be put into an extension method.

public static class SocketExtensions
{
  public static bool IsConnected(this Socket @this)
  {
    return !(@this.Poll(1, SelectMode.SelectRead) && @this.Available == 0);
  }
}

Now you can easily use it in your code dealing with sockets.

var mySocket = new Socket();
while(mySocket.IsConncted())
{
  // Do Stuff
}

Upvotes: 3

Samuel
Samuel

Reputation: 38346

Try checking the Available property, it should throw a SocketException when the connection has been closed.

Source

Edit, here is how you would use it:

while(socket.Connected)
{
  try
  {
    while (socket.Available == 0)
      System.Threading.Thread.Sleep(100); // Zzzz
  }
  catch (SocketException)
  {
    // connection closed
    // do something
  }

  /* Do some processing */
}

You could also try using the Poll method.

From Source:

Alternatively, you can also utilize the Poll() Socket method with the SelectRead SelectMode parameter. This method will return a true value if data is available or if the connection has been closed by the remote host. You will then need to differentiate between which of these situations has occurred (by reading the socket buffer, and seeing if it returns a zero value).

Upvotes: 1

Svish
Svish

Reputation: 158051

Maybe the SendTimeout and/or ReadTimeout properties of the Socket could help?

Upvotes: 0

George Mauer
George Mauer

Reputation: 122092

Spawn another thread that is constantly pinging the server - really the best you can do since a socket is not an active connection.

Upvotes: 1

Erick
Erick

Reputation: 6089

Have you tried to set a shorter connection timeout ?

Upvotes: -1

Related Questions