【发布时间】:2014-01-08 14:58:11
【问题描述】:
我正在连接到 Socket 服务器以发送和接收消息。当消息进出时一切正常,但每隔一段时间就会失去连接。我试图捕捉异常并重新连接到服务器。 失去连接时的第一个异常:
System.IO.IOException:无法从传输连接读取数据:已建立的连接被主机中的软件中止。 ---> System.Net.Sockets.SocketException:已建立的连接被主机中的软件中止 在 System.Net.Sockets.Socket.Receive(Byte[] 缓冲区,Int32 偏移量,Int32 大小,SocketFlags socketFlags) 在 System.Net.Sockets.NetworkStream.Read(Byte[] 缓冲区,Int32 偏移量,Int32 大小)
然后当它尝试重新连接时:
System.ObjectDisposedException:无法访问已处置的对象。 对象名称:“System.Net.Sockets.NetworkStream”。 在 System.Net.Sockets.NetworkStream.Read(Byte[] 缓冲区,Int32 偏移量,Int32 大小)
我的问题是我做错了什么?重新连接到服务器的最佳解决方案是什么? 我的代码如下所示:
class Test
{
private TcpClient myTcpClient;
private NetworkStream myStream;
private string host = xxx.xxx.xxx;
private int port = 8888;
private string streaming = "";
public void Listen()
{
this.myTcpClient = new TcpClient(host, port);
this.myStream = this.myTcpClient.GetStream();
Listener();
}
private void Listener()
{
try
{
while (true)
{
byte[] numResponse = new byte[8192];
int x = this.myStream.Read(numResponse, 0, numResponse.Length);
Decrypt(numResponse, 0, x);
string stream = Encoding.UTF8.GetString(numResponse);
this.streaming = string.Concat(this.streaming, stream);
}
}
catch(Excpetion ex)
{
// write ex.ToString() to TextFile
this.myTcpClient = new TcpClient(host, port);
this.myStream = this.myTcpClient.GetStream();
Listener();
}
}
}
【问题讨论】:
-
不相关,但您没有使用 myStream.Read 的返回值。这始终是一个错误。使用 StreamReader 从 NetworkStream 中读取。您的 Unicode 解码也被破坏了,因为数据包可能被任意拆分。