我有一段代码可以在 TCP 端口上“侦听”,并且无论发送什么,都只会返回一个字符串。问题是客户端只是在测试端口是否处于活动状态然后断开连接。此时我会抛出一个错误。无法访问已处置的对象对象名称:“System.Net.Socket.NetworkSystem”
我认为问题在于这段代码在一个线程上,当连接关闭时,while循环引用了一个已处理的对象......当客户端关闭连接时,我应该如何防止错误触发?
//Cretae listener to accept client connections
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
int bytesRcvd; // Received byte count
while (ServiceRunning) // Run forever, accepting and servicing connections
{
try
{
// Receive until client closes connection, indicated by 0 return value
int totalBytesEchoed = 0;
//I THINK THIS IS WHERE THE PROBLEM IS .. THE CLIENTSTREAM.READ???
while (((bytesRcvd = clientStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) && (ServiceRunning))
{
clientStream.Write(responseBytes, 0, responseBytes.Length);
WriteEventToWindowsLog("GSSResponderService", "Received "+System.Text.Encoding.UTF8.GetString(rcvBuffer), System.Diagnostics.EventLogEntryType.Information);
totalBytesEchoed += bytesRcvd;
}
WriteEventToWindowsLog("GSSResponderService", "Responded to " + totalBytesEchoed.ToString() + " bytes.", System.Diagnostics.EventLogEntryType.Information);
// Close the stream and socket. We are done with this client!
clientStream.Close();
tcpClient.Close();
}
catch (Exception e)
{
//THIS IS GETTING TRIGGERED WHEN A CONNECTION IS LOST
WriteEventToWindowsLog("GSSResponderService", "Error:" + e.Message, System.Diagnostics.EventLogEntryType.Error);
clientStream.Close();
tcpClient.Close();
break;
}
}
}