using System; using System.Net; using System.Text; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Sockets; namespace LocalhostMES.Core { public class WorkOrderNotifyTcpClient : IDisposable { private readonly TcpClient _tcpClient; private readonly string _host; private readonly int _port; public event Action MessageReceived; public event Action LogReceived; public WorkOrderNotifyTcpClient(string host, int port) { _host = host; _port = port; _tcpClient = new TcpClient(); var config = new TouchSocketConfig(); config.SetRemoteIPHost(new IPHost(IPAddress.Parse(_host), _port)); config.SetTcpDataHandlingAdapter(() => new NormalDataHandlingAdapter()); config.ConfigurePlugins(a => { a.UseTcpReconnection(); }); _tcpClient.Setup(config); _tcpClient.Connected = OnConnected; _tcpClient.Closed = OnClosed; _tcpClient.Received = OnReceived; } public bool IsConnected => _tcpClient.Online; public async Task ConnectAsync() { if (_tcpClient.Online) { return; } await _tcpClient.ConnectAsync(); } public void Disconnect() { if (_tcpClient.Online) { _tcpClient.Close(); } } private Task OnConnected(ITcpClient client, ConnectedEventArgs e) { LogReceived?.Invoke($"TCP客户端已连接 {_host}:{_port}"); return EasyTask.CompletedTask; } private Task OnClosed(ITcpClient client, ClosedEventArgs e) { LogReceived?.Invoke("TCP客户端已断开"); return EasyTask.CompletedTask; } private Task OnReceived(ITcpClient client, ReceivedDataEventArgs e) { var text = e.ByteBlock.Span.ToString(Encoding.UTF8); LogReceived?.Invoke($"TCP收到消息: {text}"); MessageReceived?.Invoke(text); return EasyTask.CompletedTask; } public void Dispose() { try { Disconnect(); } catch { } _tcpClient.Dispose(); } } }