using HighWayIot.Log4net; using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; using TcpClient = TouchSocket.Sockets.TcpClient; namespace HighWayIot.TouchSocket { public class TouchSocketTcpClient { /// /// 日志 /// private static LogHelper _logHelper = LogHelper.Instance; /// /// 懒加载 /// private static readonly Lazy lazy = new Lazy(() => new TouchSocketTcpClient()); public static TouchSocketTcpClient Instance => lazy.Value; /// /// 所有的客户端 /// public Dictionary Clients = new Dictionary(); public Action GetMessageAction; public async Task CreateTcpClient(string ip, string port) { TcpClient tcpClient = new TcpClient(); tcpClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接 tcpClient.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接 tcpClient.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。 tcpClient.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接 tcpClient.Received = async (client, e) => { GetMessageAction.Invoke(e.ByteBlock.Span.ToArray(), client.IP); }; //接收信号 await tcpClient.SetupAsync(new TouchSocketConfig() .SetRemoteIPHost($"{ip}:{port}") .ConfigureContainer(a => { a.AddConsoleLogger();//添加一个日志注入 }) .ConfigurePlugins(a => { a.UseTcpReconnection() .UsePolling(TimeSpan.FromSeconds(1)); }) ); Result result = Result.Default; //不断尝试重连 do { _logHelper.Info($"连接{ip}:{port}"); result = await tcpClient.TryConnectAsync(); } while (!result.IsSuccess); _logHelper.Info($"{ip}:{port}连接成功"); Clients.Add(ip, tcpClient); return true; } /// /// 信息发送 /// /// Bytes /// public async Task Send(string ip, byte[] message) { try { await Clients[ip].SendAsync(message); return true; } catch (Exception e) { _logHelper.Error("发送数据发生错误" + e); return false; } } /// /// 客户端释放 /// /// /// public async Task DisposeClient(string ip) { try { await Clients[ip].CloseAsync(); Clients[ip].Dispose(); Clients.Remove(ip); return true; } catch (Exception e) { _logHelper.Error("释放客户端发生错误" + e); return false; } } } }