Listening for an Ethernet cable disconnect event for a TCP server application

I have a C # TCP server application. I detect disconnected TCP clients when disconnected from the server, but how can I detect a cable disconnect event? When I disconnect the Ethernet cable, I cannot detect a disconnect.

+4
source share
4 answers

You might want to use the pinging function, which will fail if the TCP connection fails. Use this code to add an extension method to Socket:

using System.Net.Sockets;

namespace Server.Sockets {
    public static class SocketExtensions {
        public static bool IsConnected(this Socket socket) {
            try {
                return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
            } catch(SocketException) {
                return false;
            }
        }
    }
}

false, . , , , SocketExceptions on Reveice/Send. , , , , .
, , , .

:

if (!socket.IsConnected()) {
    /* socket is disconnected */
}
+1

. . . , , .

As a parameter, SocketI use the server socket on the server side from the received connection and on the client side the client connected to the server.

public bool IsConnected(Socket socket)    
{
    try
    {
        // this checks whether the cable is still connected 
        // and the partner pc is reachable
        Ping p = new Ping();

        if (p.Send(this.PartnerName).Status != IPStatus.Success)
        {
            // you could also raise an event here to inform the user
            Debug.WriteLine("Cable disconnected!");
            return false;
        }

        // if the program on the other side went down at this point
        // the client or server will know after the failed ping 
        if (!socket.Connected)
        {
            return false;
        }

        // this part would check whether the socket is readable it reliably
        // detected if the client or server on the other connection site went offline
        // I used this part before I tried the Ping, now it becomes obsolete
        // return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);

    }
    catch (SocketException) { return false; }
}
0
source

This problem can also be resolved by setting the KeepAlive socket parameter as follows:

   socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
   socket.SetKeepAliveValues(new SocketExtensions.KeepAliveValues
   {
       Enabled = true,
       KeepAliveTimeMilliseconds = 9000,
       KeepAliveIntervalMilliseconds = 1000
   });

You can configure these settings to determine how often checks are performed to verify that the connection is correct. Send Tcp KeepAlive initiates the connector itself to detect a disconnected network cable.

0
source

All Articles