TcpServerCommunicator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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;
  11. using System.Net.Sockets;
  12. using System.Runtime.InteropServices;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace Edge.Core.Processor.Communicator
  17. {
  18. [MetaPartsDescriptor(
  19. "lang-zh-cn:Tcp(本程序为服务器端)通讯器lang-en-us:Tcp(as server) communicator",
  20. "lang-zh-cn:基于TCP/IP技术的通讯器, FC作为服务器端等待客户端连接lang-en-us:TCP/IP based communicator, FC as the server and wait for connections")]
  21. public class TcpServerCommunicator<T> : ICommunicator<byte[], T> where T : MessageTemplateBase
  22. {
  23. private CancellationTokenSource readAsyncCancellationTokenSource;
  24. private DateTime? lastReceiveMsgDataFromTcpClientDateTime;
  25. private System.Timers.Timer clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer;
  26. //protected static NLog.Logger logger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("Communicator");
  27. protected ILogger logger = NullLogger.Instance;
  28. public static int tcpReceiveBufferSize = 1500;
  29. private Edge.Core.Parser.BinaryParser.ParserBase parser;
  30. private int localTcpServerListeningPort;
  31. protected TcpListener tcpListener;
  32. private TcpClient exclusiveTcpClient;
  33. private string exclusiveTcpClient_ClientRemoteEndPoint_Str = "?:?";
  34. //private bool isTcpConnBrokenDuringWrite = false;
  35. private object syncObject = new object();
  36. private object syncObject_Feed = new object();
  37. /// <summary>
  38. /// 0 for not started, 1 for started.
  39. /// </summary>
  40. private int isStarted = 0;
  41. protected bool disposed = false;
  42. private IMessageCutter<byte[]> messageCutter;
  43. //private List<MessageTemplateBase> continueParseStack = new List<MessageTemplateBase>();
  44. public event EventHandler OnConnected;
  45. public event EventHandler OnDisconnected;
  46. public event EventHandler<CommunicatorErrorMessageReadEventArg> OnErrorMessageRead;
  47. public event EventHandler<CommunicatorEventArg<byte[], T>> OnRawDataWriting;
  48. public event EventHandler<CommunicatorEventArg<byte[], T>> OnDataReceived;
  49. /// <summary>
  50. /// fired once raw data read from underlying tcp connection, without message cutting yet.
  51. /// </summary>
  52. protected Action<byte[]> OnRawDataReceived;
  53. public string Identity { get; set; }
  54. [ParamsJsonSchemas("TcpServerCommunicatorCtorSchema")]
  55. public TcpServerCommunicator(IMessageCutter<byte[]> binaryMsgCutter,
  56. Edge.Core.Parser.BinaryParser.ParserBase parser,
  57. int localTcpServerTcpListeningPortNumber,
  58. int enableClientSideActiveDetection,
  59. string enableClientSideIdentityRegistration,
  60. string enableClientSideConnLevelHeartbeat,
  61. string customLoggerFileName,
  62. IServiceProvider services)
  63. {
  64. this.Identity = "*:" + localTcpServerTcpListeningPortNumber;
  65. if (services != null)
  66. {
  67. var loggerFactory = services.GetRequiredService<ILoggerFactory>();
  68. this.logger = loggerFactory.CreateLogger("Communicator");
  69. if (!string.IsNullOrEmpty(customLoggerFileName))
  70. if (customLoggerFileName == "*")
  71. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Comm_" + localTcpServerTcpListeningPortNumber);
  72. else
  73. this.logger = loggerFactory.CreateLogger("DynamicPrivate_Comm_" + customLoggerFileName);
  74. }
  75. this.messageCutter = binaryMsgCutter;
  76. this.parser = parser;
  77. //this.remoteTcpServerListeningIpAddress = localTcpServerListeningIpAddress;
  78. this.localTcpServerListeningPort = localTcpServerTcpListeningPortNumber;
  79. if (this.messageCutter != null)
  80. {
  81. this.messageCutter.OnInvalidMessageRead += (____, ______) =>
  82. {
  83. var loggingStr = $"Bytes msg from tcp client: {exclusiveTcpClient_ClientRemoteEndPoint_Str} Read Invalid data, detail: {(______?.Message ?? "")}";
  84. this.logger.LogInformation(loggingStr);
  85. this.OnErrorMessageRead?.Invoke(this, new CommunicatorErrorMessageReadEventArg(null, loggingStr));
  86. };
  87. this.messageCutter.OnMessageCut += (s, _) =>
  88. {
  89. this.lastReceiveMsgDataFromTcpClientDateTime = DateTime.Now;
  90. var eventArg = new CommunicatorEventArg<byte[], T>();
  91. try
  92. {
  93. eventArg.Data = this.messageCutter.Message;
  94. eventArg.Message = this.parser.Deserialize(this.messageCutter.Message.ToArray()) as T;
  95. if (logger.IsEnabled(LogLevel.Debug))
  96. this.logger.LogDebug(" Parsed: " + eventArg.Message.ToLogString());
  97. }
  98. catch (Exception ex)
  99. {
  100. var loggingStr = "Message from " + exclusiveTcpClient_ClientRemoteEndPoint_Str
  101. + " exceptioned in deserilaizing bytes:\r\n 0x" + this.messageCutter.Message.ToHexLogString() + "\r\n exception detail:\r\n" + ex;
  102. this.logger.LogError(loggingStr);
  103. this.OnErrorMessageRead?.Invoke(this, new CommunicatorErrorMessageReadEventArg(this.messageCutter.Message, loggingStr));
  104. return;
  105. }
  106. try
  107. {
  108. this.OnDataReceived?.Invoke(this, eventArg);
  109. }
  110. catch (Exception ex)
  111. {
  112. this.logger.LogError("Message from " + exclusiveTcpClient_ClientRemoteEndPoint_Str
  113. + " exceptioned in handle message:\r\n" + eventArg.Message.ToLogString() + "\r\n exceptioned detail: \r\n" + ex);
  114. }
  115. };
  116. }
  117. if (enableClientSideActiveDetection > 0)
  118. {
  119. this.clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer = new System.Timers.Timer();
  120. this.clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer.Interval = 2000;
  121. this.clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer.Elapsed += (s, a) =>
  122. {
  123. //null indicates this communicator just started
  124. if (this.lastReceiveMsgDataFromTcpClientDateTime == null) return;
  125. if (DateTime.Now.Subtract(this.lastReceiveMsgDataFromTcpClientDateTime ?? DateTime.MinValue).TotalSeconds >= enableClientSideActiveDetection
  126. && this.exclusiveTcpClient != null)
  127. {
  128. this.logger.LogInformation($"Long time no see data from tcp client with: { this.exclusiveTcpClient_ClientRemoteEndPoint_Str }, will actively disconnect it...");
  129. this.readAsyncCancellationTokenSource?.Cancel();
  130. }
  131. };
  132. this.clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer.Start();
  133. }
  134. }
  135. public void Dispose()
  136. {
  137. try
  138. {
  139. this.readAsyncCancellationTokenSource?.Cancel();
  140. }
  141. catch { }
  142. this.isStarted = 0;
  143. this.tcpListener?.Stop();
  144. this.clientSideActiveDetectionByCheckingLongTimeNoSeeDataIncomingWatchTimer?.Stop();
  145. this.disposed = true;
  146. }
  147. public virtual async Task<bool> Stop()
  148. {
  149. this.Dispose();
  150. return true;
  151. }
  152. public virtual Task<bool> Start()
  153. {
  154. if (0 == Interlocked.CompareExchange(ref this.isStarted, 1, 0))
  155. {
  156. try
  157. {
  158. this.tcpListener = new TcpListener(IPAddress.Any, this.localTcpServerListeningPort);
  159. this.tcpListener.Start();
  160. this.logger.LogInformation($"TcpListener listened on localPort: {this.localTcpServerListeningPort}");
  161. var _ = Task.Run(async () =>
  162. {
  163. while (this.isStarted == 1)
  164. {
  165. logger.LogInformation($"Waitting for connection on localPort: {this.localTcpServerListeningPort}");
  166. var newTcpClient = await this.tcpListener.AcceptTcpClientAsync();
  167. this.logger.LogInformation($" A tcp client with remote ip/port: {newTcpClient.Client.RemoteEndPoint} has connected in");
  168. if (this.exclusiveTcpClient != null)
  169. {
  170. logger.LogInformation($" There's already a previous TcpClient established as exclusive, so close this new one with remote ip/port: {newTcpClient.Client.RemoteEndPoint}");
  171. try
  172. {
  173. newTcpClient.Close();
  174. }
  175. catch { }
  176. continue;
  177. }
  178. this.exclusiveTcpClient = newTcpClient;
  179. this.exclusiveTcpClient_ClientRemoteEndPoint_Str = this.exclusiveTcpClient.Client.RemoteEndPoint.ToString();
  180. this.logger.LogInformation($" Tcp client with remote ip/port: {this.exclusiveTcpClient_ClientRemoteEndPoint_Str} has been chosen as exclusive");
  181. var ___ = Task.Run(async () =>
  182. {
  183. #region try set the tcp client with TCP keepalive feature, but seems does not work.
  184. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  185. {
  186. }
  187. else
  188. {
  189. //logger.LogInformation($"Enabled tcp keep alive for tcpClient");
  190. //overall switch to enable the feature.
  191. this.exclusiveTcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
  192. //when entering tcp idle, how much time wait before send a KeepAlive package.
  193. this.exclusiveTcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 20);
  194. //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.
  195. this.exclusiveTcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 8);
  196. //when in tcp idle, how many KeepAlive package response have not received will treat as tcp broken, and trigger tcp disconnected exception.
  197. this.exclusiveTcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3);
  198. }
  199. #endregion
  200. this.lastReceiveMsgDataFromTcpClientDateTime = DateTime.Now;
  201. this.OnConnected?.Invoke(this, null);
  202. while (this.isStarted == 1)
  203. {
  204. this.readAsyncCancellationTokenSource = new CancellationTokenSource();
  205. byte[] buffer = new byte[tcpReceiveBufferSize];
  206. int bytesReadCount;
  207. try
  208. {
  209. bytesReadCount = await this.exclusiveTcpClient.GetStream().ReadAsync(buffer, this.readAsyncCancellationTokenSource.Token);
  210. if (bytesReadCount == 0)
  211. throw new Exception("tcp server received 0 count data indicates the connection is broken");
  212. if (logger.IsEnabled(LogLevel.Debug))
  213. this.logger.LogDebug($"TCP from { this.exclusiveTcpClient_ClientRemoteEndPoint_Str } <---Incoming: 0x" + buffer.Take(bytesReadCount).ToHexLogString());
  214. }
  215. catch (Exception eeee)
  216. {
  217. logger.LogError($"tcp client with remote ip/port: {this.exclusiveTcpClient_ClientRemoteEndPoint_Str} exceptioned in GetStream().ReadAsync(), treat as tcp disconnection, detail: {eeee}");
  218. try
  219. {
  220. this.exclusiveTcpClient.Close();
  221. }
  222. finally { this.exclusiveTcpClient = null; }
  223. try
  224. {
  225. this.OnDisconnected?.Invoke(this, null);
  226. }
  227. catch { }
  228. break;
  229. }
  230. var data = buffer.Take(bytesReadCount).ToArray();
  231. try
  232. {
  233. this.OnRawDataReceived?.Invoke(data);
  234. }
  235. catch { }
  236. try
  237. {
  238. lock (this.syncObject_Feed)
  239. {
  240. this.messageCutter.Feed(data, this.localTcpServerListeningPort);
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. this.logger.LogError($"Exception in Parsing msg bytes: 0x{ buffer.Take(bytesReadCount).ToHexLogString()}, detail: {Environment.NewLine}{ ex.ToString()}");
  246. }
  247. }
  248. });
  249. }
  250. });
  251. return Task.FromResult(true);
  252. }
  253. catch (Exception exxx)
  254. {
  255. logger.LogError($"Start tcp listener on port: {this.localTcpServerListeningPort} exceptioned: {exxx}");
  256. return Task.FromResult(false);
  257. }
  258. }
  259. return Task.FromResult(false);
  260. }
  261. public bool Write(T message)
  262. {
  263. if (this.exclusiveTcpClient == null)
  264. {
  265. //if (this.logger.IsEnabled(LogLevel.Trace))
  266. // this.logger.LogTrace($"Write failed as no tcp client connected in yet");
  267. return false;
  268. }
  269. if (message == null) return false;
  270. byte[] rawData;
  271. try
  272. {
  273. rawData = this.parser.Serialize(message);
  274. var arg = new CommunicatorEventArg<byte[], T>() { Data = rawData, Message = message, Continue = true };
  275. this.OnRawDataWriting?.Invoke(this, arg);
  276. if (this.exclusiveTcpClient == null || !arg.Continue) { this.logger.LogError("Write failed, this.tcpClient is null: " + (this.exclusiveTcpClient is null)); return false; }
  277. }
  278. catch (Exception exx)
  279. {
  280. var msgLogStr = "";
  281. try
  282. {
  283. msgLogStr = message.ToLogString();
  284. }
  285. catch
  286. {
  287. msgLogStr = "exceptioned for get ToLogString()";
  288. }
  289. this.logger.LogError("Tcp Write failed in serialize or event raise for msg: " + message.GetType() + " -> " + msgLogStr + "\r\n detail: " + exx);
  290. return false;
  291. }
  292. lock (this.syncObject)
  293. {
  294. try
  295. {
  296. if (logger.IsEnabled(LogLevel.Debug))
  297. this.logger.LogDebug("TCP to " + (this.exclusiveTcpClient_ClientRemoteEndPoint_Str) + " Outgoing--->: " + message.ToLogString() + "\r\n 0x" + rawData.ToHexLogString());
  298. var sendCount = this.exclusiveTcpClient.Client.Send(rawData);
  299. if (sendCount == 0)
  300. throw new InvalidOperationException("the send count in this.exclusiveTcpClient.Client.Send is 0");
  301. }
  302. catch (Exception exx)
  303. {
  304. this.logger.LogError("Send tcp msg to "
  305. + (this.exclusiveTcpClient_ClientRemoteEndPoint_Str) + " Write(...) exceptioned, treat as a broken tcp connection, will cancel the data read as well, detail: " + exx);
  306. try
  307. {
  308. this.readAsyncCancellationTokenSource.Cancel();
  309. }
  310. catch { }
  311. this.OnDisconnected?.Invoke(this, null);
  312. }
  313. }
  314. return true;
  315. }
  316. public bool Write(T message, object extraControlParameter)
  317. {
  318. throw new NotImplementedException();
  319. }
  320. }
  321. }