0

I am trying to create a server/client program but when my internet (server host) disconnects the clients thinks they still connected but they are not (ofcourse). When I close the server just normally by closing the process it works perfectly fine. The code I use to check if the connection is still alive:

 if (_clientSocket != null)
                {
                    if (firstConnect != true)
                    {
                        if (!_clientSocket.Connected)
                        {
                            Console.WriteLine("Not connected");
                            LoopConnect();
                        }
                        else
                        {
                            Console.WriteLine("Connected");
                        }
                    }
                }
                Thread.Sleep(1000);
            }

I've also tried to replace if (!_clientSocket.Connected) with if (!SocketConnected(_clientSocket) with this method:

static bool SocketConnected(Socket s)
        {
            bool part1 = s.Poll(1000, SelectMode.SelectRead);
            bool part2 = (s.Available == 0);
            if (part1 && part2)
                return false;
            else
                return true;
        }

but both go to the else and print Connected. I am clueless why this happends only when my internet disconnects and not when I close the server normally. Thanks in advance!

ManoDestra
  • 5,756
  • 6
  • 22
  • 48
Jesse Vlietveld
  • 293
  • 1
  • 11
  • Try searching. You can't detect a non-graceful disconnect until you try to write. – CodeCaster Apr 12 '16 at 15:03
  • As an aside, you can simplify some of your boolean logic here. In your first code snippet: could simply be `if (!firstConnect)` and in your SocketConnection method: `return !part1 || !part2, rather than your if-else construct. It's long winded and unnecessary. Let the boolean logic do the work for you :) – ManoDestra Apr 12 '16 at 15:04

0 Answers0