2012-04-24 36 views

回答

0

您可能想要應用「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
+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

0

我發現這個方法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; } 
} 
相關問題