.net – C# TCP Socket Programming – Determining whether a connection has been dropped – Education Career Blog

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

,

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

,

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

Leave a Comment