我是C#的新手,我之所以选择它,是因为我必须为客户端编写服务器监听器...我将构建一个带有线程的服务器,可以无故障地监听多个客户端,但有时当客户端断开服务器连接时错误。
System.InvalidOperationException:不允许不连接的操作
这是我接收数据包的代码:
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 312);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
string hex = BitConverter.ToString(bytesFrom).Replace("-","");
Console.WriteLine("\n " + hex + "\n_______________()()()______________");
这是控制台屏幕截图,显示错误: Screenshot Link
答案 0 :(得分:2)
TcpClient.GetStream()将抛出异常。
将代码包装在try..catch块中:
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 312);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
string hex = BitConverter.ToString(bytesFrom).Replace("-","");
Console.WriteLine("\n " + hex + "\n_______________()()()______________");
}
catch (InvalidOperationException ioex)
{
// The TcpClient is not connected to a remote host.
}
catch (ObjectDisposedException odex)
{
// The TcpClient has been closed.
}