TcpClientBase.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. using SKMC.Api.Common.Logger;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace SKMC.Api.Common.Tcp
  9. {
  10. public class TcpClientBase
  11. {
  12. protected static readonly ILogger log = LogFactory.Get();
  13. public string Address { get; set; } = "127.0.0.1";
  14. public int Port { get; set; }
  15. public int TIMEOUT { get; set; } = 5000;
  16. // 是否长连接
  17. public bool KeepAlived { get; set; } = false;
  18. // 测试模式(空跑模式)下, 不等待接收响应
  19. public bool TestMode { get; set; } = false;
  20. // 是否开启
  21. public bool Enabled { get; set; } = true;
  22. public bool Logged { get; set; } = true;
  23. // 是否运行中, 结束运行可放弃等待服务端响应数据
  24. public bool Running { get; set; }
  25. private TCPClient client;
  26. public TcpClientBase(string address, int port)
  27. {
  28. Address = address;
  29. Port = port;
  30. client = new TCPClient(Address, Port) { KeepAlived = KeepAlived };
  31. }
  32. /// <summary>
  33. /// 保持连接, 如果连接已中断则重新连接
  34. /// </summary>
  35. /// <param name="mills">验证连接的超时时间(ms)</param>
  36. /// <returns></returns>
  37. public TCPClient Connect(int mills)
  38. {
  39. if (!Enabled) return null;
  40. if (!KeepAlived || !client.IsConnected(mills))
  41. {
  42. client.Connect();
  43. }
  44. return client;
  45. }
  46. public TCPClient Connect()
  47. {
  48. if (!Enabled) return null;
  49. if (client != null) client.Connect();
  50. return client;
  51. }
  52. public void Reset(int index)
  53. {
  54. if (client != null) client.Clear();
  55. Running = false;
  56. }
  57. /// <summary>
  58. /// 请求并获取结果
  59. /// 请求后阻塞获取确认消息
  60. /// 再异步接收结果
  61. /// </summary>
  62. /// <param name="requestMsg">请求消息</param>
  63. /// <param name="responseAction">响应结果解析</param>
  64. /// <returns></returns>
  65. public Task RequestAndResult(string requestMsg, bool sync = false, Action<string> responseAction = null, Action<string> resultAction = null)
  66. {
  67. string response = null;
  68. string result = null;
  69. try
  70. {
  71. client = Connect(100);
  72. Reset(0);
  73. client.Send(requestMsg, Logged);
  74. response = client.Recevie(Logged);
  75. if (sync)
  76. {
  77. resultAction?.Invoke(response);
  78. if (!KeepAlived) client.Close();
  79. }
  80. else
  81. {
  82. // 异步模式, 视觉采图响应
  83. try
  84. {
  85. responseAction?.Invoke(response);
  86. }
  87. catch (Exception e)
  88. {
  89. throw new Exception($"Response Parse(Aync) Error", e);
  90. }
  91. }
  92. if (sync) return null;
  93. return Task.Run(() =>
  94. {
  95. try
  96. {
  97. result = client.Recevie(Logged);
  98. resultAction?.Invoke(result);
  99. if (!KeepAlived) client.Close();
  100. }
  101. catch (Exception e)
  102. {
  103. throw new Exception($"Result Parse(Aync) Error", e);
  104. }
  105. });
  106. }
  107. catch (SocketException ex)
  108. {
  109. switch ((SocketError)ex.ErrorCode)
  110. {
  111. case SocketError.TimedOut:
  112. throw new Exception($"接收超时: [{Address} : {Port}]", ex);
  113. case SocketError.ConnectionRefused:
  114. throw new Exception($"连接被拒绝: [{Address} : {Port}]", ex);
  115. case SocketError.HostNotFound:
  116. throw new Exception($"地址未找到: [{Address} : {Port}]", ex);
  117. case SocketError.NetworkDown:
  118. throw new Exception($"网络不可用: [{Address} : {Port}]", ex);
  119. case SocketError.AddressAlreadyInUse:
  120. throw new Exception($"地址已被使用: [{Address} : {Port}]", ex);
  121. default:
  122. throw new Exception($"其他Socket异常: [{Address} : {Port}]", ex);
  123. }
  124. }
  125. catch (Exception e)
  126. {
  127. throw e;
  128. }
  129. }
  130. }
  131. }