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 readonly Lazy lazy = new Lazy(() => new TouchSocketTcpClient()); public static TouchSocketTcpClient Instance => lazy.Value; /// /// 所有的客户端 /// public Dictionary Clients = new Dictionary(); public int ClientsCount = 0; public Action GetMessageAction; public bool 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 = (client, e) => { var mes = e.Memory.Span.ToString(Encoding.UTF8); GetMessageAction.Invoke(e.Memory.Span.ToArray(), client.IP); tcpClient.Logger.Info($"客户端接收到信息:{mes}"); return EasyTask.CompletedTask; //GetMessageAction.Invoke(e.ByteBlock.Span.ToArray(), client.IP); //return EasyTask.CompletedTask; }; //接收信号 tcpClient.SetupAsync(new TouchSocketConfig() .SetRemoteIPHost($"{ip}:{port}") .ConfigureContainer(a => { a.AddConsoleLogger();//添加一个日志注入 }) .ConfigurePlugins(a => { a.UseReconnection(options => { options.PollingInterval = TimeSpan.FromSeconds(1); }); }) ); Result result = Result.Default; //不断尝试重连 do { result = tcpClient.TryConnectAsync().GetAwaiter().GetResult(); Task.Delay(1000).Wait(); } while (!result.IsSuccess); if (Clients.ContainsKey(ip)) { Clients.Remove(ip); Clients.Add(ip, tcpClient); } else { Clients.Add(ip, tcpClient); } return true; } /// /// 信息发送 /// /// Bytes /// public bool Send(string ip, byte[] message) { try { if (Clients.ContainsKey(ip)) { Clients[ip].SendAsync(message); return true; } else { return false; } } catch (Exception e) { return false; } } /// /// 客户端释放 /// /// /// public bool DisposeClient(string ip) { try { if (Clients.ContainsKey(ip)) { Clients[ip].CloseAsync(); Clients[ip].Dispose(); Clients.Remove(ip); } else { return false; } return true; } catch (Exception e) { return false; } } } }