using log4net; using NewLife.Net.Handlers; using SlnMesnac.RfidUpload.Model.model; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; namespace SlnMesnac.RfidUpload.TouchSocket { public class TouchSocketService : ITouchSocketService { private static readonly log4net.ILog log = LogManager.GetLogger(typeof(TouchSocketService)); /// /// 扫码业务触发事件 /// /// public delegate void ReceiveCodeDelegate(string code); public static event ReceiveCodeDelegate? ReceiveCodeDelegateEvent; /// ///刷新连接状态 /// /// public delegate void RefreshStateDelegate(bool status); public static event RefreshStateDelegate? RefreshStateDelegateEvent; TcpService service; #region 初始化构造函数 public TouchSocketService() { } #endregion #region Socket 初始化 public Task> AddTouchSocketAsync(string RFIDAdress) { MessageModel messageModel = new MessageModel(); service = new TcpService(); service.Connecting = (client, e) => { client.Logger.Info($"{client.IP}:{client.Port} 客户端正在连接..."); RefreshStateDelegateEvent?.Invoke(true); return EasyTask.CompletedTask; };//有客户端正在连接 service.Connected = (client, e) => { client.Logger.Info($"{client.IP}:{client.Port} 客户端连接成功!目前客户端连接数{service.Count}"); RefreshStateDelegateEvent?.Invoke(true); return EasyTask.CompletedTask; };//有客户端成功连接 service.Disconnected += (client, e) => { //有客户端断开连接 client.Logger.Info($"{client.IP}:{client.Port}客户端断开!"); RefreshStateDelegateEvent?.Invoke(false); //RefreshStateEvent?.Invoke(client.IP, false); return EasyTask.CompletedTask; }; service.Received = (client, e) => { #region 原始Buffer byte[] receivedBuffer = new byte[e.ByteBlock.Len]; Array.Copy(e.ByteBlock.Buffer, 0, receivedBuffer, 0, e.ByteBlock.Len); #endregion try { var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len if(mes.Length %22 ==0) { // 拆分混合数据 SplitMixedData(mes); } //if (mes.Length == 22 && mes.StartsWith("RFID") && mes.EndsWith("0D")) //{ // // 去掉帧头 "RFID" 和帧尾 "0D" // string trimmedMes = mes.Substring(4, mes.Length - 6); // 去掉前4个字符和后2个字符 // ReceiveCodeDelegateEvent?.Invoke(trimmedMes); //} } catch (Exception ex) { client.Logger.Error($"异常:{ex.Message}"); log.Error($"异常:{ex.Message}"); } return EasyTask.CompletedTask; }; service.Setup(new TouchSocketConfig()//载入配置 .SetListenIPHosts(new IPHost[] { new IPHost($"{RFIDAdress}") })//可同时监听两个地址 // .SetDataHandlingAdapter(() => { return new NormalDataHandlingAdapter(); })//配置适配器 .SetMaxCount(10000) //.SetThreadCount(1000) //.SetCacheTimeoutEnable(false) .ConfigureContainer(a => { a.AddConsoleLogger(); }) .ConfigurePlugins(a => { a.UseCheckClear(); })); service.Start();//启动 service.Logger.Info("服务器成功启动"); messageModel.success = true; messageModel.msg = "OK"; return Task.FromResult(messageModel); } static void SplitMixedData(string mixedData) { int index = 0; while (index < mixedData.Length) { // 查找 "RFID" 的起始位置 int startIndex = mixedData.IndexOf("RFID", index); if (startIndex == -1) { break; } // 检查从起始位置开始长度为 22 的子字符串是否以 "0D" 结尾 if (startIndex + 22 <= mixedData.Length && mixedData.Substring(startIndex, 22).EndsWith("0D")) { string singleData = mixedData.Substring(startIndex, 22); // 去掉帧头 "RFID" 和帧尾 "0D" string trimmedMes = singleData.Substring(4, singleData.Length - 6); // 触发事件 ReceiveCodeDelegateEvent?.Invoke(trimmedMes); // 输出拆分后的数据 Console.WriteLine(trimmedMes); index = startIndex + 22; } else { index = startIndex + 1; } } } #endregion } }