-5

我是 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_______________()()()______________");

这是带有错误的控制台屏幕截图: 屏幕截图链接

4

1 回答 1

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.
}
于 2013-02-26T11:48:03.423 回答