using Admin.Core.Common;
using Admin.Core.Socket.TSocket;
using log4net;
using System.Text;
using System.Threading;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace Admin.Core.Socket
{
public class TouchSocketService : ITouchSocketService
{
private static readonly log4net.ILog log = LogManager.GetLogger(typeof(TouchSocketService));
///
/// 刷新扫码器状态
///
///
///
public delegate void RefreshState(string ip, bool flag);
public static event RefreshState RefreshStateEvent;
///
/// 门体匹配扫码
///
///
public delegate Task DoorReceiveCodeDelegate(string code);
public static event DoorReceiveCodeDelegate? DoorReceiveCodeDelegateEvent;
TcpService service;
#region 初始化构造函数
public TouchSocketService()
{
}
#endregion
#region Socket 初始化
public Task> AddTouchSocketAsync()
{
MessageModel messageModel = new MessageModel();
service = new TcpService();
service.Connecting = (client, e) => { client.Logger.Info($"{client.IP}:{client.Port} 客户端正在连接..."); };//有客户端正在连接
service.Connected = (client, e) => { client.Logger.Info($"{client.IP}:{client.Port} 客户端连接成功!目前客户端连接数{service.Count}"); };//有客户端成功连接
service.Disconnected += (client, e) => { //有客户端断开连接
client.Logger.Info($"{client.IP}:{client.Port}客户端断开!");
RefreshStateEvent?.Invoke(client.IP, true);
};
service.Received = (client, byteBlock, requestInfo) =>
{
try
{
var mes = Encoding.UTF8.GetString(byteBlock.Buffer, 0, byteBlock.Len);//注意:数据长度是byteBlock.Len
//心跳包
if (mes== "heartbeat")
{
//扫码器连接
client.Logger.Info($"已从{client.IP}:{client.Port}》接收到心跳信息:{mes}");
RefreshStateEvent?.Invoke(client.IP,true);
}
else if (mes.Contains("heartbeat"))
{
//扫码器连接
client.Logger.Info($"已从{client.IP}:{client.Port}》接收到心跳信息:{mes}");
RefreshStateEvent?.Invoke(client.IP, true);
}
else if (mes == "NoRead")
{
client.Logger.Info($"未从{client.IP}:{client.Port}》接收到二维码信息{mes}");
}
else
{
DoorReceiveCodeDelegateEvent?.Invoke(mes);
client.Logger.Info($"已从{client.IP}:{client.Port}》接收到信息:{mes}");
}
}
catch (Exception ex)
{
client.Logger.Error($"异常:{ex.Message}");
}
};
service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost(Appsettings.app("Middleware", "TouchSocket", "Address").ObjToString()) })//可同时监听两个地址
.SetDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); })//配置适配器
.SetMaxCount(10000)
//.SetThreadCount(1000)
//.SetCacheTimeoutEnable(false)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
a.UseCheckClear();
}))
.Start();//启动
service.Logger.Info("服务器成功启动");
messageModel.success = true;
messageModel.msg = "OK";
return Task.FromResult(messageModel);
}
#endregion
}
}