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 SocketConnect { public void SocketMonitor() { var service = new TcpService(); service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接 service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接 service.Disconnecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。 service.Disconnected = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接 service.Received = (client, e) => { //从客户端收到信息 var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意:数据长度是byteBlock.Len client.Logger.Info($"已从{client.Id}接收到信息:{mes}"); return EasyTask.CompletedTask; }; service.Setup(new TouchSocketConfig()//载入配置 .SetListenIPHosts("192.168.11.211:6501", "192.168.11.212:6502", "192.168.11.213:6503", "192.168.11.214:6504")//同时监听两个地址 .ConfigureContainer(a =>//容器的配置顺序应该在最前面 { a.AddConsoleLogger();//添加一个控制台日志注入(注意:在maui中控制台日志不可用) }) .ConfigurePlugins(a => { //a.Add();//此处可以添加插件 })); service.Start();//启动 } } }