Wednesday, 7 October 2009

How to Check Whether a Socket Is Still Connected?

Socket class has a property called Connected. This Connected property doesn't specify whether the socket is now connected or not but it returns true if the Socket was connected to a remote resource as of the most recent operation; otherwise, false. What this means is that Microsoft is better to rename this property to "WasConnected" rather than "Connected".

The following method helps to determine whether a socket is now connected (Indeed, it pings the socket):

public static bool IsSocketStillConnected(Socket socket)
{
bool connected = true;
bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[1];
// Setting Blocking to false makes the execution not to wait until it's complete
socket.Blocking = false;
socket.Send(tmp, 0, 0);
}
catch (SocketException e)
{
connected = false;
}
finally
{
socket.Blocking = blockingState;
}
return connected;
}

Even if you use this method, there is still a millisecond gap, you see?

if (IsSocketStillConnected(mySocket))
{
mySocket.Send(message);
}

What this means is that the best practice is:

Whenever you want to Send or Receive a message using a Socket whether synchronously or asynchronously, you should wrap it with a try/catch block.

No comments: