using Microsoft.Extensions.Logging; using SlnMesnac.Config; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; namespace SlnMesnac.TouchSocket { public class TcpServer { private DebugConfig config = DebugConfig.Instance; private ILogger _logger; private readonly TcpService _service; #region 委托事件 /// /// 刷新扫码器状态 /// /// /// public delegate void RefreshState(string ip, bool flag); public static event RefreshState RefreshStateEvent; //NoRead事件通知 //public delegate void MessageNoRead(); //public static event MessageNoRead MessageNoReadEvent; //扫码事件 public delegate void RefreshMaterialCodeStr(string materialCodeStr, string ip); public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent; //相机拍照识别结果事件 public delegate void CameraResult(string result); public static event CameraResult CameraResultEvent; #endregion public TcpServer(ILogger logger,TcpService tcpService) { _logger = logger; _service = tcpService; } public void Init(int serverPort) { try { Console.WriteLine("启动Socket服务"); _service.Connecting = (client, e) => { _logger.LogInformation($"客户端{client.IP}正在接入服务"); return EasyTask.CompletedTask; }; _service.Connected = (client, e) => { _logger.LogInformation($"客户端{client.IP}接入服务成功"); RefreshStateEvent?.Invoke(client.IP, true); return EasyTask.CompletedTask; }; _service.Disconnected = (client, e) => { _logger.LogInformation($"客户端{client.IP}断开连接"); RefreshStateEvent?.Invoke(client.IP, false); return EasyTask.CompletedTask; }; _service.Received = (client, e) => { try { //从客户端收到信息 var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len //心跳包 if (mes == "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}》NoRead事件{mes}"); // TODO } else { string code = mes.Trim().TrimEnd('\0'); client.Logger.Info($"客户端{client.IP}:{client.Port}》接收到信息:{mes}"); // 区分相机扫码器数据 if (client.IP == config.ScannerIP) { if (code.Contains("heart")) { // 粘包丢弃 return Task.CompletedTask; } RefreshMaterialCodeStrEvent?.Invoke(code, client.IP); } else if (client.IP == config.CameraIP) { // 相机返回数据 CameraResultEvent?.Invoke(code); } } } catch (Exception ex) { _logger.LogError($"socket接收数据异常:{ex.Message}"); } return EasyTask.CompletedTask; }; _service.Setup(new TouchSocketConfig()//载入配置 .SetListenIPHosts(new IPHost[] { new IPHost($"0.0.0.0:{serverPort}") }) .ConfigureContainer(a =>//容器的配置顺序应该在最前面 { a.AddConsoleLogger(); }) .ConfigurePlugins(a => { //自定义插件 })); _service.Start(); _logger.LogInformation($"TcpServer启动成功,监听端口:{serverPort}"); } catch (Exception ex) { //throw new InvalidOperationException($"TcpServer启动异常:{ex.Message}"); _logger.LogError($"TcpServer启动异常:{ex.Message}"); } } /// /// 向所有客户端发送心跳 /// //public void SendHeartBeat() //{ // var clients = _service.SocketClients.GetClients(); // foreach (var item in clients) // { // _service.Send(item.Id, "heartbeat"); // } //} /// /// 向指定相机发送指令 /// public void SendCommand(string ip, string command) { ISocketClient client = _service.SocketClients.GetClients().FirstOrDefault(x => x.IP ==ip); if (client != null) { _service.Send(client.Id, command); } } } }