using HighWayIot.Log4net; using System; 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; TcpClient client = new TcpClient(); public async void TcpClient(string ip, string port) { client.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接 client.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接 client.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。 client.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接 client.Received = async (client, e) => { //从客户端收到信息 var mes = e.ByteBlock.Span.ToString(Encoding.UTF8); client.Logger.Info($"已从{client.IP}接收到信息:{mes}"); }; await client.SetupAsync(new TouchSocketConfig() .SetRemoteIPHost($"{ip}:{port}") .ConfigureContainer(a => { a.AddConsoleLogger();//添加一个日志注入 })); Result result = Result.Default; //不断尝试重连 do { result = await client.TryConnectAsync(); } while (!result.IsSuccess); return; } /// /// 信息发送 /// /// Bytes /// public async Task Send(byte[] message) { try { await client.SendAsync(message); return true; } catch (Exception e) { _logHelper.Error("发送数据发生错误" + e); return false; } } } }