我正在使用TcpClient。有时出错:NetStream TcpClinet无法从传输连接读取数据
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
我试图通过来自stackoverflow贡献的信息来解决。我补充条件
netStream.CanRead
但没有成功。我做错了什么? 这里是部分代码,谢谢。
try
{
if (netStream.CanRead)
{
do
{
int bytesRead = netStream.Read(bytes, 0, bytes.Length);
bytesReaded += bytesRead;
if (bytesRead > 0)
{
byte[] toList = new byte[bytesRead];
Array.Copy(bytes, toList, bytesRead);
listBytes.AddRange(toList);
}
}
while (netStream.DataAvailable);
if (listBytes.Count > 0)
ParseAllBytes();
}
else
{
Close();
}
}
catch (IOException ex)
{
这将很难用wireshark,因此这个错误是不是周期性的。 有了这个问题,断开连接后,客户端无法再连接到TcpClient。我必须重新启动服务。这个问题与错误有关吗? – Musketyr
除非正确设置了重用套接字,否则您可能需要重新创建套接字或TcpClient。我从来没有得到它的工作。我总是创造一个全新的插座。我不确定TcpClient是否与套接字具有相同的重用思路。 – uriDium
在TcpClient的新实例中,处理传入的数据针对新线程中的每个客户端。错误是TcpClient和NetStream正确处置后。 – Musketyr