Click here to Skip to main content
15,888,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C#
<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

 
Share this answer
 
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?
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();
}
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900