C#“有时”套接字侦听器在客户端断开连接后发出错误

时间:2013-02-26 11:42:31

标签: c# sockets error-handling console

我是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

1 个答案:

答案 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.
}