我在使用 C# 编写的托管 Windows 服务中工作。它不断从通过 TCP/IP 连接的多个客户端接收消息。客户端基本上是一个路由器,用于接收温度计的消息并将其重新发送到服务器。服务器解析消息并将它们存储在 SQL Server 数据库中。
我面临的问题是某些客户端突然停止发送消息。但是,一旦服务重新启动,它们就会再次连接并继续发送。我没有客户端的代码,因为它是第三方设备,我很确定问题出在服务器上。
我设法通过实现一个计时器来减少问题,该计时器不断检查每个客户端是否仍处于连接状态(请参见下面的代码)。此外,我使用 socket.IOControl(IOControlCode.KeepAliveValues, ...)
方法向 Socket 添加了 Keep Alive 模式,但问题仍然存在。
我正在发布一些我认为相关的特定部分的代码。但是,如果需要更多片段来理解问题,请询问我,我将编辑帖子。删除了所有 try/catch block 以减少代码量。
我不想要一个完美的解决方案,只要任何指导,我将不胜感激。
private Socket _listener;
private ConcurrentDictionary<int, ConnectionState> _connections;
public TcpServer(TcpServiceProvider provider, int port)
{
this._provider = provider;
this._port = port;
this._listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._connections = new ConcurrentDictionary<int, ConnectionState>();
ConnectionReady = new AsyncCallback(ConnectionReady_Handler);
AcceptConnection = new WaitCallback(AcceptConnection_Handler);
ReceivedDataReady = new AsyncCallback(ReceivedDataReady_Handler);
}
public bool Start()
{
this._listener.Bind(new IPEndPoint(IPAddress.Any, this._port));
this._listener.Listen(10000);
this._listener.BeginAccept(ConnectionReady, null);
}
// Check every 5 minutes for clients that have not send any message in the past 30 minutes
// MSG_RESTART is a command that the devices accepts to restart
private void CheckForBrokenConnections()
{
foreach (var entry in this._connections)
{
ConnectionState conn = entry.Value;
if (conn.ReconnectAttemptCount > 3)
{
DropConnection(conn);
continue;
}
if (!conn.Connected || (DateTime.Now - conn.LastResponse).TotalMinutes > 30)
{
byte[] message = HexStringToByteArray(MSG_RESTART);
if (!conn.WaitingToRestart && conn.Write(message, 0, message.Length))
{
conn.WaitingToRestart = true;
}
else
{
DropConnection(conn);
}
}
}
}
private void ConnectionReady_Handler(IAsyncResult ar)
{
lock (thisLock)
{
if (this._listener == null)
return;
ConnectionState connectionState = new ConnectionState();
connectionState.Connection = this._listener.EndAccept(ar);
connectionState.Server = this;
connectionState.Provider = (TcpServiceProvider)this._provider.Clone();
connectionState.Buffer = new byte[4];
Util.SetKeepAlive(connectionState.Connection, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME);
int newID = (this._connections.Count == 0 ? 0 : this._connections.Max(x => x.Key)) + 1;
connectionState.ID = newID;
this._connections.TryAdd(newID, connectionState);
ThreadPool.QueueUserWorkItem(AcceptConnection, connectionState);
this._listener.BeginAccept(ConnectionReady, null);
}
}
private void AcceptConnection_Handler(object state)
{
ConnectionState st = state as ConnectionState;
st.Provider.OnAcceptConnection(st);
if (st.Connection.Connected)
st.Connection.BeginReceive(st.Buffer, 0, 0, SocketFlags.None, ReceivedDataReady, st);
}
private void ReceivedDataReady_Handler(IAsyncResult result)
{
ConnectionState connectionState = null;
lock (thisLock)
{
connectionState = result.AsyncState as ConnectionState;
connectionState.Connection.EndReceive(result);
if (connectionState.Connection.Available == 0)
return;
// Here the message is parsed
connectionState.Provider.OnReceiveData(connectionState);
if (connectionState.Connection.Connected)
connectionState.Connection.BeginReceive(connectionState.Buffer, 0, 0, SocketFlags.None, ReceivedDataReady, connectionState);
}
}
internal void DropConnection(ConnectionState connectionState)
{
lock (thisLock)
{
if (this._connections.Values.Contains(connectionState))
{
ConnectionState conn;
this._connections.TryRemove(connectionState.ID, out conn);
}
if (connectionState.Connection != null && connectionState.Connection.Connected)
{
connectionState.Connection.Shutdown(SocketShutdown.Both);
connectionState.Connection.Close();
}
}
}
最佳答案
我认为我看到的 2 件事...
如果这是您为多条消息保留的连接,当
connectionState.Connection.Available == 0
IIRC a 0 时,您可能不应该从ReceivedDataReady_Handler
返回可以接收长度数据包。因此,如果连接仍然打开,您应该在离开处理程序之前调用connectionState.Connection.BeginReceive( ... )
。(我不太愿意把它放在这里,因为我不记得具体细节)有一个事件可以告诉你你的基础连接何时发生事情,包括错误和失败连接或关闭连接。对于我的生活,我不记得名字了......这可能比每隔几秒的计时器更有效。它还为您提供了一种断开卡在连接或关闭状态的连接的方法。
关于C# TCP 服务器停止接收客户端消息,在服务重新启动时恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902671/