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

问题描述:

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

您可能想要应用“ping”功能,如果发生TCP连接丢失,该功能将失败。使用此代码将扩展方法添加到套接字:

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 */ 
} 
+1

不,它没有工作。我可以检测到我的电缆拔下事件,但我无法检测到tcp客户端的拔下事件。 – sanchop22 2012-04-24 14:21:37

+0

请提供downvote的信息? – moka 2013-08-05 15:28:56

+0

它没有工作。 – sanchop22 2012-04-24 13:43:05

+1

它用于拔掉服务器的电缆。我如何检测拔掉客户端的电缆? – sanchop22 2012-04-24 13:46:16

+1

@你不能。服务器无法知道客户端正在进行什么操作。唯一的办法就是ping它,看看它是否响应。或者当CableUnplugged事件发生时,您可以尝试从客户端发送消息以通知服务器; - ) – 2012-04-24 14:20:20

我发现这个方法here。它检查连接的不同状态并发出断开信号。但未检测到拔下的电缆。经过进一步的搜索和反复试验,我终于解决了这个问题。

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