Click here to Skip to main content
14,330,041 members
Rate this:
Please Sign up or sign in to vote.
How to detect closed TCP connection when Client disconnected disgracfully i.e sudden power off ?


Following method don't work when client disconnects disgracefully.

What I have tried:

<pre>if (socket != null)
                    {
                        bool part1 = socket.Poll(1000, SelectMode.SelectRead);
                        bool part2 = (socket.Available == 0);
                        if (part1 && part2)
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    else
                        return false;
Posted
Updated 23-Apr-19 20:54pm
Rate this:
Please Sign up or sign in to vote.

Solution 2

   
Comments
DoingWork 14-May-19 0:54am
   
Keep Alive mode solves 50%. But if dont have option to make client as Keep Alive then what will be option?
Rate this:
Please Sign up or sign in to vote.

Solution 1

I used something like this:
bool connectedLocal = true;

using (var socketTemp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
 {
     socketTemp.Connect(ip, port);

     // Loop until prg finished or connection is lost.
     while (Running && connectedLocal)
     {
         Thread.CurrentThread.Join(100);
         connectedLocal = !(socketTemp.Poll(0, SelectMode.SelectRead) && socketTemp.Available == 0);
     }

     socketTemp.Close();
}
   
v2
Comments
DoingWork 24-Apr-19 2:44am
   
It fails when connected client disconnects disgracefully. i.e. fail to send disconnect to network due to power shutdown.
RickZeeland 24-Apr-19 3:33am
   
That's strange, in our network it works as expected, maybe it has something to do with your network configuration ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100