4

我有一个 C# TCP 服务器应用程序。当 TCP 客户端与服务器断开连接时,我检测到它们断开连接,但是如何检测电缆拔出事件?当我拔下以太网电缆时,我无法检测到断开连接。

4

4 回答 4

1

您可能想要应用“ping”功能,如果 TCP 连接丢失,该功能将失败。使用此代码向 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。即使您在 Reveice / Send 方法上没有 SocketExceptions,它也应该可以检查是否存在连接。请记住,如果您遇到与连接丢失相关的错误消息的异常,则不再需要检查连接。
当套接字看起来像已连接但可能与您的情况不同时,应使用此方法。

用法:

if (!socket.IsConnected()) {
    /* socket is disconnected */
}
于 2012-04-24T14:14:11.673 回答
0

尝试NetworkAvailabilityChanged事件。

于 2012-04-24T13:37:08.203 回答
0

我在这里找到了这个方法。它检查连接的不同状态并发出断开连接的信号。但没有检测到拔下的电缆。经过进一步的搜索和反复试验,这就是我最终解决它的方法。

作为Socket参数,我在服务器端使用来自已接受连接的客户端套接字,在客户端使用连接到服务器的客户端。

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; }
}
于 2016-06-08T09:36:32.143 回答
0

这个问题也可以通过设置 KeepAlive 套接字选项来解决,如下所示:

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

可以调整这些选项以设置检查的频率,以确保连接有效。Tcp KeepAlive的发送会触发socket自身检测网线断开。

于 2019-05-08T13:44:43.000 回答