using HighWayIot.Log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; namespace HighWayIot.TouchSocket { public class TcpServer { private static readonly Lazy lazy = new Lazy(() => new TcpServer()); public static TcpServer Instance => lazy.Value; private static LogHelper logHelper = LogHelper.Instance; public ServerState State { get => service.ServerState; private set => State = value; } TcpService service = new TcpService(); public bool ServerStart(string ip, string port) { try { service.Connecting = (client, e) => { logHelper.Info($"客户端{client.IP}正在连接"); return EasyTask.CompletedTask; };//有客户端正在连接 service.Connected = (client, e) => { logHelper.Info($"客户端{client.IP}成功连接"); return EasyTask.CompletedTask; };//有客户端成功连接 service.Disconnecting = (client, e) => { logHelper.Info($"客户端{client.IP}正在断开连接"); return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。 service.Disconnected = (client, e) => { logHelper.Info($"客户端{client.IP}断开连接"); return EasyTask.CompletedTask; };//有客户端断开连接 service.Received = (client, e) => { ////从客户端收到信息 //var mes = Encoding.ASCII.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len //logHelper.Info($"已从{client.IP}:{client.Port}接收到信息:{mes}"); BufferMemory(Encoding.ASCII.GetString(BufferAnalysis.SplitByteArray(e.ByteBlock.Buffer, 0, e.ByteBlock.Len)), client.IP); return EasyTask.CompletedTask; }; service.Setup(new TouchSocketConfig()//载入配置 .SetListenOptions(option => { option.Add(new TcpListenOption() { IpHost = ip + ":" + port, Name = "Server",//名称用于区分监听 ServiceSslOption = null,//可以针对当前监听,单独启用ssl加密 Adapter = () => new NormalDataHandlingAdapter(),//可以单独对当前地址监听,配置适配器 //还有其他可配置项,都是单独对当前地址有效。 }); }) .ConfigureContainer(a =>//容器的配置顺序应该在最前面 { a.AddConsoleLogger();//添加一个控制台日志注入(注意:在maui中控制台日志不可用) }) .ConfigurePlugins(a => { //a.Add();//此处可以添加插件 })); service.Start();//启动 logHelper.Info("监听服务启动成功"); return true; } catch (Exception ex) { logHelper.Error("监听服务启动失败! 错误代码" + ex.ToString()); return false; } } public bool ServerStop() { try { service.Stop(); logHelper.Info("监听服务关闭成功!"); return true; } catch (Exception ex) { logHelper.Error("监听服务关闭失败! 错误代码" + ex.ToString()); return false; } } public bool ServerDispose() { try { service.Dispose(); logHelper.Info("监听服务释放成功!"); return true; } catch (Exception ex) { logHelper.Error("监听服务释放失败! 错误代码" + ex.ToString()); return false; } } private void BufferMemory(string json, string ip) { JObject obj = JsonConvert.DeserializeObject(json); if (obj["status"] != null) { string str = obj["status"].Value(); if (str == "HEART") { BufferAnalysis.HeartbeatSocket(ip); } else if (str == "WARNNING") { BufferAnalysis.RFIDStatusSocket(ip); } else if (str == "GR" || str == "NR") { BufferAnalysis.RFIDCodeSocket(obj, ip); } else { logHelper.Info($"{str}为未知类型!"); } } else { logHelper.Info($"输入格式错误!"); } } } }