TcpClientCommunicator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using Edge.Core.Parser.BinaryParser.MessageEntity;
  2. using Edge.Core.Parser.BinaryParser.Util;
  3. using Edge.Core.Processor.Dispatcher.Attributes;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Logging;
  6. using Microsoft.Extensions.Logging.Abstractions;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net.Sockets;
  11. using System.Runtime.InteropServices;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace Edge.Core.Processor.Communicator
  16. {
  17. [MetaPartsDescriptor(
  18. "lang-zh-cn:Tcp(本机为客户端)通讯器lang-en-us:Tcp(as client) communicator",
  19. "lang-zh-cn:基于TCP/IP技术的通讯器, FC作为客户端主动连接服务器端lang-en-us:TCP/IP based communicator, FC as the client side and connecting to Server side")]
  20. public class TcpClientCommunicator<T> : ICommunicator<byte[], T> where T : MessageTemplateBase
  21. {
  22. //protected static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Communicator");
  23. protected ILogger logger = NullLogger.Instance;
  24. public static int tcpReceiveBufferSize = 1500;
  25. private Edge.Core.Parser.BinaryParser.ParserBase parser;
  26. private string remoteTcpServerListeningIpAddress;
  27. private int remoteTcpServerListeningPortNumber;
  28. protected TcpClient tcpClient;
  29. /// <summary>
  30. /// 0 is for false, 1 is for true.
  31. /// </summary>
  32. private int isInTcpConnecting = 0;
  33. private object syncObject = new object();
  34. private object syncObject_Feed = new object();
  35. private bool enableTcpKeepAlive = true;
  36. /// <summary>
  37. /// 0 for not started, 1 for started.
  38. /// </summary>
  39. private int isStarted = 0;
  40. protected bool disposed = false;
  41. private IMessageCutter<byte[]> messageCutter;
  42. //private List<MessageTemplateBase> continueParseStack = new List<MessageTemplateBase>();
  43. public event EventHandler OnConnected;
  44. public event EventHandler OnDisconnected;
  45. public event EventHandler<CommunicatorErrorMessageReadEventArg> OnErrorMessageRead;
  46. public event EventHandler<CommunicatorEventArg<byte[], T>> OnRawDataWriting;
  47. public event EventHandler<CommunicatorEventArg<byte[], T>> OnDataReceived;
  48. /// <summary>
  49. /// fired once raw data read from underlying tcp connection, without message cutting yet.
  50. /// </summary>
  51. protected Action<byte[]> OnRawDataReceived;
  52. public string Identity { get; set; }
  53. [ParamsJsonSchemas("TcpClientCommunicatorCtorSchema")]
  54. public TcpClientCommunicator(IMessageCutter<byte[]> binaryMsgCutter,
  55. Edge.Core.Parser.BinaryParser.ParserBase parser,
  56. string remoteTcpServerListeningIpAddress,
  57. int remoteTcpServerTcpListeningPortNumber,
  58. string customLoggerFileName,
  59. IServiceProvider services)
  60. {
  61. this.Identity = remoteTcpServerListeningIpAddress + ":" + remoteTcpServerTcpListeningPortNumber;
  62. if (services != null)
  63. {
  64. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  65. this.logger = loggerFactory.CreateLogger("Communicator");
  66. if (!string.IsNullOrEmpty(customLoggerFileName))
  67. if (customLoggerFileName == "*")
  68. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Comm_" + remoteTcpServerListeningIpAddress + "_" + remoteTcpServerTcpListeningPortNumber);
  69. else
  70. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Comm_" + customLoggerFileName);
  71. }
  72. this.messageCutter = binaryMsgCutter;
  73. this.parser = parser;
  74. this.remoteTcpServerListeningIpAddress = remoteTcpServerListeningIpAddress;
  75. this.remoteTcpServerListeningPortNumber = remoteTcpServerTcpListeningPortNumber;
  76. if (this.messageCutter != null)
  77. {
  78. this.messageCutter.OnInvalidMessageRead += (____, ______) =>
  79. {
  80. var loggingStr = $"Message from {this.remoteTcpServerListeningIpAddress}:{this.remoteTcpServerListeningPortNumber} Read Invalid data, detail: {(______?.Message ?? "")}";
  81. this.logger.LogInformation(loggingStr);
  82. this.OnErrorMessageRead?.Invoke(this, new CommunicatorErrorMessageReadEventArg(null, loggingStr));
  83. };
  84. this.messageCutter.OnMessageCut += (s, _) =>
  85. {
  86. var eventArg = new CommunicatorEventArg<byte[], T>();
  87. try
  88. {
  89. eventArg.Data = this.messageCutter.Message;
  90. eventArg.Message = this.parser.Deserialize(this.messageCutter.Message.ToArray()) as T;
  91. if (logger.IsEnabled(LogLevel.Debug))
  92. this.logger.LogDebug(" Parsed: " + eventArg.Message.ToLogString());
  93. }
  94. catch (Exception ex)
  95. {
  96. var loggingStr = "Message from " + this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber
  97. + " exceptioned in deserilaizing bytes:\r\n 0x" + this.messageCutter.Message.ToHexLogString() + "\r\n exception detail:\r\n" + ex;
  98. this.logger.LogError(loggingStr);
  99. this.OnErrorMessageRead?.Invoke(this, new CommunicatorErrorMessageReadEventArg(this.messageCutter.Message, loggingStr));
  100. return;
  101. }
  102. try
  103. {
  104. this.OnDataReceived?.Invoke(this, eventArg);
  105. }
  106. catch (Exception ex)
  107. {
  108. this.logger.LogError(this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber
  109. + " exceptioned in handle message:\r\n" + eventArg.Message.ToLogString() + "\r\n exceptioned detail: \r\n" + ex);
  110. }
  111. };
  112. }
  113. }
  114. public void Dispose()
  115. {
  116. this.tcpClient?.Close();
  117. this.disposed = true;
  118. }
  119. public virtual Task<bool> Start()
  120. {
  121. if (0 == Interlocked.CompareExchange(ref this.isStarted, 1, 0))
  122. {
  123. try
  124. {
  125. this.SetupTcpClientConnectionInBackground();
  126. return Task.FromResult(true);
  127. }
  128. catch (Exception exxx)
  129. {
  130. return Task.FromResult(false);
  131. }
  132. }
  133. return Task.FromResult(false);
  134. }
  135. public bool Write(T message)
  136. {
  137. if (message == null) return false;
  138. byte[] rawData;
  139. try
  140. {
  141. rawData = this.parser.Serialize(message);
  142. var safe = this.OnRawDataWriting;
  143. var arg = new CommunicatorEventArg<byte[], T>() { Data = rawData, Message = message, Continue = true };
  144. safe?.Invoke(this, arg);
  145. if (this.tcpClient == null || !arg.Continue) { this.logger.LogError("Write failed, this.tcpClient is null? " + (this.tcpClient is null)); return false; }
  146. }
  147. catch (Exception exx)
  148. {
  149. var msgLogStr = "";
  150. try
  151. {
  152. msgLogStr = message.ToLogString();
  153. }
  154. catch
  155. {
  156. msgLogStr = "exceptioned for get ToLogString()";
  157. }
  158. this.logger.LogError("Tcp Write failed in serialize or event raise for msg: " + message.GetType() + " -> " + msgLogStr + "\r\n detail: " + exx);
  159. return false;
  160. }
  161. lock (this.syncObject)
  162. {
  163. try
  164. {
  165. if (this.isInTcpConnecting == 1) return false;
  166. if (logger.IsEnabled(LogLevel.Debug))
  167. this.logger.LogDebug("TCP to " + this.tcpClient.Client.RemoteEndPoint + " Outgoing--->: " + message.ToLogString() + "\r\n 0x" + rawData.ToHexLogString());
  168. this.tcpClient.Client.Send(rawData);
  169. }
  170. catch (Exception exx)
  171. {
  172. this.logger.LogError("Send tcp msg to "
  173. + this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber + " Write(...) exceptioned, will re-build connection, detail: " + exx);
  174. var _ = this.OnDisconnected;
  175. _?.Invoke(this, null);
  176. this.SetupTcpClientConnectionInBackground();
  177. }
  178. }
  179. return true;
  180. }
  181. public bool Write(T message, object extraControlParameter)
  182. {
  183. throw new NotImplementedException();
  184. }
  185. /// <summary>
  186. /// connect to remote pump, FC as the client side.
  187. /// </summary>
  188. /// <returns></returns>
  189. private void SetupTcpClientConnectionInBackground()
  190. {
  191. if (0 == Interlocked.CompareExchange(ref this.isInTcpConnecting, 1, 0))
  192. ThreadPool.QueueUserWorkItem(o =>
  193. {
  194. while (!this.disposed)
  195. {
  196. try
  197. {
  198. this.logger.LogInformation("FCC as the tcp client side is establishing to remote tcp server "
  199. + this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber);
  200. if (this.tcpClient != null) this.tcpClient.Dispose();
  201. this.tcpClient = new TcpClient(this.remoteTcpServerListeningIpAddress, this.remoteTcpServerListeningPortNumber);
  202. if (this.enableTcpKeepAlive)
  203. {
  204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  205. {
  206. }
  207. else
  208. {
  209. //overall switch to enable the feature.
  210. this.tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  211. //when entering tcp idle, how much time wait before send a KeepAlive package.
  212. this.tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 20);
  213. //when in tcp idle, and failed to received previous KeepAlive response, sequence of KeepAlive packages will send by this interval, until response received, or TcpKeepAliveRetryCount reached.
  214. this.tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 8);
  215. //when in tcp idle, how many KeepAlive package response have not received will treat as tcp broken, and trigger tcp disconnected exception.
  216. this.tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3);
  217. }
  218. }
  219. logger.LogInformation("FCC has established to remote tcp server("
  220. + this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber
  221. + "), local port: " + this.tcpClient.Client.LocalEndPoint.ToString());
  222. byte[] buffer = new byte[tcpReceiveBufferSize];
  223. this.tcpClient.GetStream().BeginRead(buffer, 0,
  224. tcpReceiveBufferSize,
  225. this.Tcp_DataReceived, new System.Tuple<TcpClient, byte[]>(this.tcpClient, buffer));
  226. this.isInTcpConnecting = 0;
  227. var _ = this.OnConnected;
  228. _?.Invoke(this, null);
  229. return;
  230. }
  231. catch (Exception exxx)
  232. {
  233. this.logger.LogError("Setup tcp client which connect to remote tcp server("
  234. + this.remoteTcpServerListeningIpAddress + ":" + this.remoteTcpServerListeningPortNumber
  235. + ") exceptioned: " + exxx + "\r\n Will keep retrying...");
  236. Thread.Sleep(3000);
  237. }
  238. }
  239. });
  240. }
  241. private void Tcp_DataReceived(IAsyncResult ar)
  242. {
  243. System.Tuple<TcpClient, byte[]> parameter = null;
  244. byte[] dataRead = null;
  245. int bytesReadCount = 0;
  246. try
  247. {
  248. parameter = (System.Tuple<TcpClient, byte[]>)(ar.AsyncState);
  249. dataRead = parameter.Item2;
  250. bytesReadCount = parameter.Item1.Client.EndReceive(ar);
  251. if (bytesReadCount == 0)
  252. throw new Exception("tcp client received 0 count data which indicates the connection is broken, trigger disconnection");
  253. }
  254. catch (Exception tcpExp)
  255. {
  256. this.logger.LogInformation("Tcp client EndReceive from " + this.remoteTcpServerListeningIpAddress + " exceptioned: " + tcpExp + "\r\n will re-build connection...");
  257. var _ = this.OnDisconnected;
  258. _?.Invoke(this, null);
  259. this.SetupTcpClientConnectionInBackground();
  260. return;
  261. }
  262. try
  263. {
  264. if (logger.IsEnabled(LogLevel.Debug))
  265. this.logger.LogDebug("TCP from " + parameter.Item1.Client.RemoteEndPoint.ToString() + " <---Incoming: 0x" + dataRead.Take(bytesReadCount).ToHexLogString());
  266. try
  267. {
  268. var data = dataRead.Take(bytesReadCount).ToArray();
  269. this.OnRawDataReceived?.Invoke(data);
  270. lock (this.syncObject_Feed)
  271. {
  272. this.messageCutter.Feed(data);
  273. }
  274. }
  275. catch (Exception ex)
  276. {
  277. this.logger.LogError(" Exception in TCP Parsing bytes: 0x" + dataRead.Take(bytesReadCount).ToHexLogString() + ", detail: \r\n" + ex.ToString());
  278. }
  279. byte[] buffer = new byte[tcpReceiveBufferSize];
  280. parameter.Item1.GetStream().BeginRead(buffer, 0,
  281. tcpReceiveBufferSize,
  282. this.Tcp_DataReceived, new System.Tuple<TcpClient, byte[]>(parameter.Item1, buffer));
  283. }
  284. catch (Exception ex)
  285. {
  286. this.logger.LogError(" Exception in Tcp_DataReceived(...):\r\n" + ex.ToString() + "\r\n will rebuild the connection until succeed.");
  287. var _ = this.OnDisconnected;
  288. _?.Invoke(this, null);
  289. this.SetupTcpClientConnectionInBackground();
  290. return;
  291. }
  292. }
  293. }
  294. }