在客戶端,我需要知道何時/如果套接字連接已斷開。然而,Socket.Connected屬性總是返回true,即使在服務器端已斷開連接並嘗試通過它發送數據之後。任何人都可以幫我弄清楚這裏發生了什麼。我需要知道套接字何時斷開連接。如何判斷套接字何時斷開
Socket serverSocket = null;
TcpListener listener = new TcpListener(1530);
listener.Start();
listener.BeginAcceptSocket(new AsyncCallback(delegate(IAsyncResult result)
{
Debug.WriteLine("ACCEPTING SOCKET CONNECTION");
TcpListener currentListener = (TcpListener)result.AsyncState;
serverSocket = currentListener.EndAcceptSocket(result);
}), listener);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, and it is
clientSocket.Connect("localhost", 1530);
Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be TRUE, and it is
Thread.Sleep(1000);
serverSocket.Close();//closing the server socket here
Thread.Sleep(1000);
clientSocket.Send(new byte[0]);//sending data should cause the socket to update its Connected property.
Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, but its always TRUE
請參閱http://stackoverflow.com/questions/722240/instantly-detect-client-disconnection-from-server-socket進一步討論。 – EricLaw 2013-07-11 22:58:04