Im连接到Socket服务器以发送和接收消息。一切工作正常,因为消息进出,但每隔一段时间它就会失去联系。我试图捕捉异常并重新连接到服务器。 连接丢失时的第一个例外:重新连接TCPClient抛出异常
System.IO.IOException:无法从传输连接读取数据:建立的连接被主机中的软件中止。 ---> System.Net.Sockets.SocketException:一个建立的连接是由软件在主机 在System.Net.Sockets.Socket.Receive中止(字节[]缓冲液,的Int32偏移的Int32大小,的SocketFlags的SocketFlags) 在System.Net.Sockets.NetworkStream.Read(字节[]缓冲液,的Int32偏移的Int32大小)
,然后当它试图重新连接:
System.ObjectDisposedException:无法访问已释放的对象。 对象名称:'System.Net.Sockets.NetworkStream'。 at System.Net.Sockets.NetworkStream.Read(Byte [] buffer,Int32 offset,Int32 size)
我的问题是我做错了什么?什么是重新连接到服务器的最佳解决方案? 我的代码看起来像这样:
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解码也被破坏,因为数据包可能被任意分割。 – usr