You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PLT-PDA/Admin.Core.Socket/HeartbeatAndReceivePlugin.cs

68 lines
2.0 KiB
C#

1 year ago
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);
}
}
}