在使用我编写的 TCP 服务器接收数据时,我遇到了随机出现神秘错误的问题。例外情况如下:
System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at TTS_Simulator.TCPChannel.ReceiveData(IAsyncResult ar)
我正在使用 BeginXXX 和 EndXXX 异步方法,对方肯定没有关闭连接。
负责接受连接的代码:
protected void AcceptCallback(IAsyncResult ar)
{
try
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
_logger.Info("Connection request accepted on local endpoint: " + listener.LocalEndPoint);
_logger.Info("Connection request accepted from remote endpoint: " + handler.RemoteEndPoint);
Thread.Sleep(100);
StateObject state = new StateObject { workSocket = handler };
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
ReceiveData, state);
IsConnected = true;
ControlActivator?.Invoke(true);
listener.BeginAccept(AcceptCallback, listener);
}
catch (SocketException ex)
{
_logger.Error(ex);
}
catch (NullReferenceException ex)
{
_logger.Error(ex);
}
}
以及负责接收消息的代码:
protected void ReceiveData(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
string _inputData = String.Empty;
int totalBytesRead = 0;
int bytesRead = 0;
try
{
bytesRead = handler.EndReceive(ar);
totalBytesRead += bytesRead;
if (totalBytesRead == 0)
{
_logger.Info("Client disconnected at: " + handler.LocalEndPoint);
handler.Disconnect(true);
handler.Close();
handler.Dispose();
IsConnected = false;
ControlActivator?.Invoke(false);
return;
}
if (totalBytesRead > 0)
{
if (handler.Available > 0)
{
bytesRead = handler.Receive(state.buffer, bytesRead, StateObject.BufferSize,
SocketFlags.None);
totalBytesRead += bytesRead;
}
}
DataHandler(handler, state.buffer, totalBytesRead);
totalBytesRead = 0;
state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, ReceiveData, state);
}
catch (System.Net.Sockets.SocketException ex)
{
_logger.Error("Error receiving data! \n" + ex);
}
catch (Exception ex)
{
_logger.Error("Error when processing the data! \n" + ex);
}
}
有时,服务器和客户端都报告完全相同的问题,有时,它只是服务器或客户端。同样有趣的是,当服务器接受连接时,我可以在日志中看到实际上有两个连接请求,都被接受了。不知道这是否与它有关......只是一个侧面说明,服务器和客户端都在同一台机器上运行,这是一个 MS Azure VM。如果需要,我还可以附上服务器的整个代码。
谢谢!