gpt4 book ai didi

C# "Sometimes"客户端断开连接后,套接字监听器出现错误

转载 作者:行者123 更新时间:2023-12-03 09:15:22 25 4
gpt4 key购买 nike

很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .




9年前关闭。




我是 C# 新手,之所以选择它,是因为我必须为客户端编写服务器监听器……我将构建一个带有线程的服务器,它可以毫无问题地监听多个客户端,但有时当客户端断开连接时,服务器会出错。

System.InvalidOperationException: the operation is not allowed non-connected



这是我接收数据包的代码:
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

最佳答案

TcpClient.GetStream()如果套接字未连接或不再连接,将抛出异常。

将代码包装在 try..catch block 中:

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

关于C# "Sometimes"客户端断开连接后,套接字监听器出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15088249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com