tags:

views:

69

answers:

2

I am trying to discover whether a TCP connection is being dropped at the server after a given interval and have written the following code;

 var tcpClient = new TcpClient();

 tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);

 tcpClient.Connect(Ip, Port);
 var status = tcpClient.Connected ? "Connected" : "Failed to Connect";

 if (connected)
 {
    Console.WriteLn(string.Format("Connected - Waiting for '{0}' to see if the connection is dropped", ConnectionDuration));
    Thread.Sleep(ConnectionDuration);
    status = tcpClient.Connected ? "Stayed Connected" : "Connection Dropped";
 }

 Console.WriteLn(string.Format("Connection Status: '{0}'", status);

With this code, if a connection is made initially I will always receive the "Stayed connected" status message.

Because the server is outside our company it's not desirable to write data to the socket, is there any other way to determine if the connection has been dropped?

Thanks

+1  A: 

Make a non-blocking zero byte Send call, if you get a WOULDBLOCK error code or success, you are still connected.

Michael Goldshteyn
You are quite correct, I shall try this and then mark as accepted if it works - http://stackoverflow.com/questions/1363682/how-do-i-make-a-non-blocking-socket-call-in-c-to-determine-connection-status
CityView
A: 

I do not think that this does what you want:

true if the Client socket was connected to a remote resource as of the most recent operation; otherwise, false.

Says MSDN

Also, setting the keepalive option will send data on the tcp level, it's just not you sending the data but the os.

I think you will have to build something around select

hth

Mario

Mario The Spoon