| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- 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<string> MessageReceived;
- public event Action<string> 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();
- }
- }
- }
|