1
客戶端斷開連接在服務器端我有這樣的代碼,其在新的線程中運行.NET插座的問題:從服務器
static void ListenForConsultant()
{
while (true)
{
var serverSocket = new TcpListener(IPAddress.Any, 2111);
serverSocket.Start();
var clientSocket = serverSocket.AcceptTcpClient();
consultantConnected = true;
Console.WriteLine(" >> Consultant Connected");
byte[] bytesFrom = new byte[10025];
while (true)
{
if (!clientSocket.Connected)
{
break;
}
NetworkStream networkStream = clientSocket.GetStream();
bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
var dataFromConsultant = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromConsultant.IndexOf("~") != -1 && dataFromConsultant.IndexOf("^") != -1 && dataFromConsultant.IndexOf("^") > dataFromConsultant.IndexOf("~"))
{
var lengthOfMessage = dataFromConsultant.IndexOf("^") - dataFromConsultant.IndexOf("~") - 1;
dataFromConsultant = dataFromConsultant.Substring(dataFromConsultant.IndexOf("~") + 1, lengthOfMessage);
Console.WriteLine(" >> From consultant:" + dataFromConsultant);
}
}
consultantConnected = false;
Console.WriteLine(" >> Consultant Disconnected");
serverSocket.Stop();
}
}
我連接使用膩子端口2111的所有工作正常,但是當我關閉膩子插座沒有按關閉,但我有條件
if (!clientSocket.Connected)
{
break;
}
調試顯示,即使從服務器斷開連接後,clientSocket.Connected爲true。
爲什麼會發生這種情況?
我應該用什麼來代替這個屬性來確定客戶端的狀態? – takayoshi
更新了答案:代碼[來自我以前的答案](http://stackoverflow.com/questions/6452992/tcpclient-disconnect-during-async-read/6455369#6455369)。 –