using Admin.Core.Socket.TSocket; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; namespace Admin.Core.Socket { public class HeartbeatAndReceivePlugin : TcpPluginBase { private readonly int m_timeTick; private readonly ILog logger; [DependencyInject(1000 * 5)] public HeartbeatAndReceivePlugin(int timeTick, ILog logger) { this.m_timeTick = timeTick; this.logger = logger; } protected override void OnConnected(ITcpClientBase client, TouchSocketEventArgs e) { if (client is ISocketClient) { return;//此处可判断,如果为服务器,则不用使用心跳。 } if (client.GetValue(DependencyExtensions.HeartbeatTimerProperty) is Timer timer) { timer.Dispose(); } client.SetValue(DependencyExtensions.HeartbeatTimerProperty, new Timer((o) => { client.Ping(); }, null, 0, m_timeTick)); base.OnConnected(client, e); } protected override void OnDisconnected(ITcpClientBase client, DisconnectEventArgs e) { base.OnDisconnected(client, e); if (client.GetValue(DependencyExtensions.HeartbeatTimerProperty) is Timer timer) { timer.Dispose(); client.SetValue(DependencyExtensions.HeartbeatTimerProperty, null); } } protected override void OnReceivedData(ITcpClientBase client, ReceivedDataEventArgs e) { if (e.RequestInfo is MyRequestInfo myRequest) { this.logger.Info(myRequest.ToString()); if (myRequest.DataType == DataType.Ping) { client.Pong(); } } base.OnReceivedData(client, e); } } }