2013-04-01 273 views
1

我正在與C#窗口應用程序窗體的TCP多線程服務器上工作,並且我正在嘗試檢測客戶端的機器是否關閉並從服務器斷開連接。我看了一些帖子,並有一些想法:C#檢測TCP客戶端斷開

How to determine if the tcp is connected or not?

Instantly detect client disconnection from server socket

但我不知道在哪裏調用函數IsConnected

我的代碼是這樣的:

public BindingList<Tablet> tabletList = new BindingList<Tablet>(); 
private Socket socket_Server = null; 
    private Thread myThread = null; 
    private Socket socket_Connect = null; 
    private Dictionary<string, Socket> dic = new Dictionary<string, Socket> { }; 
    private string RemoteEndPoint; 

socket_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     IPAddress ServerIP = IPAddress.Parse("192.168.2.146"); 
     IPEndPoint point = new IPEndPoint(ServerIP, portNum); 
     socket_Server.Bind(point); 
     socket_Server.Listen(50); 
     myThread = new Thread(Listen_Disp); 
     myThread.IsBackground = true; 
     myThread.Start(); 
     Console.WriteLine("Server start"); 

private void Listen_Disp() 
    { 
     try 
     { 
      while (true) 
      { 

       //This is not working 
       for (int i = 0; i < tabletList.Count; i++) 
       { 
        if (!SocketConnected(dic[tabletList[i].ip])) 
        { 
         Console.WriteLine(RemoteEndPoint + "disconnected"); 
        } 
       } 

       try 
       { 
        socket_Connect = socket_Server.Accept(); 
        RemoteEndPoint = socket_Connect.RemoteEndPoint.ToString(); 
        Console.WriteLine(RemoteEndPoint + " is connected"); 
        dic.Add(RemoteEndPoint, socket_Connect); 

        Tablet newTablet = new Tablet(); 
        newTablet.ip = RemoteEndPoint; 
        newTablet.status = "Online"; 
        tabletList.Add(newTablet); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.ToString()); 
       } 
      } 

      Console.WriteLine("end of while"); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 
    } 

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

感謝您的幫助。

回答

3

關於該主題有很多錯誤信息,其中一些信息出現在您鏈接的問題中。檢測TCP斷開的唯一可靠方法是嘗試寫入連接。讀取超時也可以指示連接斷開,但也可能意味着很多其他事情,例如卡住的服務器。閱讀時的EOS條件表示正常斷開連接。 IsConnected()方法和朋友只會給你一個你對這個套接字做過什麼的歷史記錄:它們不會給你連接的當前狀態。他們不能,因爲沒有待處理的寫請求,所以不知道 。 TCP不保持類似撥號音的任何內容。

+0

那麼,如果我只想知道我的客戶還活着還是不活躍,那麼最簡單的方法是什麼?繼續收到心跳? – AkariKamigishi

+0

其實對我來說真正的問題是,我不知道在哪裏放置心跳代碼 – AkariKamigishi

+0

這只是你如何組織代碼的問題。由於您尚未發佈任何內容,因此其他人不可能發表評論。 – EJP