侦听TCP服务器应用程序的以太网电缆拔出事件

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

您可能希望应用“ping”function,如果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。 请记住,如果您的exception有与连接丢失相关的错误消息,那么您不再需要检查连接。
当socket看起来像连接时,可以使用此方法,但可能与您的情况不同。

用法:

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

尝试NetworkAvailabilityChanged事件。

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

作为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; } }