WorkOrderNotifyTcpClient.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Net;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using TouchSocket.Core;
  6. using TouchSocket.Sockets;
  7. namespace LocalhostMES.Core
  8. {
  9. public class WorkOrderNotifyTcpClient : IDisposable
  10. {
  11. private readonly TcpClient _tcpClient;
  12. private readonly string _host;
  13. private readonly int _port;
  14. public event Action<string> MessageReceived;
  15. public event Action<string> LogReceived;
  16. public WorkOrderNotifyTcpClient(string host, int port)
  17. {
  18. _host = host;
  19. _port = port;
  20. _tcpClient = new TcpClient();
  21. var config = new TouchSocketConfig();
  22. config.SetRemoteIPHost(new IPHost(IPAddress.Parse(_host), _port));
  23. config.SetTcpDataHandlingAdapter(() => new NormalDataHandlingAdapter());
  24. config.ConfigurePlugins(a => { a.UseTcpReconnection(); });
  25. _tcpClient.Setup(config);
  26. _tcpClient.Connected = OnConnected;
  27. _tcpClient.Closed = OnClosed;
  28. _tcpClient.Received = OnReceived;
  29. }
  30. public bool IsConnected => _tcpClient.Online;
  31. public async Task ConnectAsync()
  32. {
  33. if (_tcpClient.Online)
  34. {
  35. return;
  36. }
  37. await _tcpClient.ConnectAsync();
  38. }
  39. public void Disconnect()
  40. {
  41. if (_tcpClient.Online)
  42. {
  43. _tcpClient.Close();
  44. }
  45. }
  46. private Task OnConnected(ITcpClient client, ConnectedEventArgs e)
  47. {
  48. LogReceived?.Invoke($"TCP客户端已连接 {_host}:{_port}");
  49. return EasyTask.CompletedTask;
  50. }
  51. private Task OnClosed(ITcpClient client, ClosedEventArgs e)
  52. {
  53. LogReceived?.Invoke("TCP客户端已断开");
  54. return EasyTask.CompletedTask;
  55. }
  56. private Task OnReceived(ITcpClient client, ReceivedDataEventArgs e)
  57. {
  58. var text = e.ByteBlock.Span.ToString(Encoding.UTF8);
  59. LogReceived?.Invoke($"TCP收到消息: {text}");
  60. MessageReceived?.Invoke(text);
  61. return EasyTask.CompletedTask;
  62. }
  63. public void Dispose()
  64. {
  65. try
  66. {
  67. Disconnect();
  68. }
  69. catch
  70. {
  71. }
  72. _tcpClient.Dispose();
  73. }
  74. }
  75. }