IOTcpClient.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. namespace Universal.IO;
  2. internal class IOTcpClient : BaseFilter, ITcpClient
  3. {
  4. #region Internal Variables
  5. public string? Name { get; internal set; }
  6. bool _bInitialize = false;
  7. volatile bool _bOpen = false;
  8. System.Net.Sockets.TcpClient? _tcpClient = null;
  9. Task? _readTask = null;
  10. TcpConnection? _tcpConnection = null;
  11. #endregion
  12. bool ITcpClient.Initiallize(string name)
  13. {
  14. lock (this)
  15. {
  16. if (_bInitialize)
  17. return false;
  18. this._bInitialize = true;
  19. this.Name = name;
  20. return true;
  21. }
  22. }
  23. bool ITcpClient.Open(string remoteHost, ushort remotePort, out TcpConnection? tcpConnection, string? localHost, ushort localPort, bool noDelay, int timeout, int receiveBufferSize)
  24. {
  25. tcpConnection = null;
  26. lock (this)
  27. {
  28. if (!_bInitialize)
  29. return false;
  30. if (_bOpen)
  31. return false;
  32. if (!IPAddress.TryParse(remoteHost, out IPAddress? remoteIPAddress) || remoteIPAddress is null)
  33. return false;
  34. AutoResetEvent? allowOpenEvent = new(false);
  35. bool result = false;
  36. try
  37. {
  38. _tcpClient = new() { NoDelay = noDelay };
  39. if (string.IsNullOrEmpty(localHost) || !IPAddress.TryParse(localHost, out IPAddress? localIP) || localIP is null)
  40. {
  41. _tcpClient = new() { NoDelay = noDelay };
  42. }
  43. else
  44. {
  45. IPEndPoint localEP = new(localIP, localPort);
  46. _tcpClient = new(localEP) { NoDelay = noDelay };
  47. }
  48. using CancellationTokenSource cancellationTokenSource = new();
  49. Task valueTask = _tcpClient.ConnectAsync(remoteIPAddress, remotePort);
  50. if (!valueTask.Wait(timeout))
  51. {
  52. cancellationTokenSource.Cancel();
  53. return false;
  54. }
  55. TcpConnection? connection = default;
  56. _readTask = Task.Factory.StartNew(async () =>
  57. {
  58. try
  59. {
  60. if (_tcpClient.Client.LocalEndPoint is not IPEndPoint || _tcpClient.Client.RemoteEndPoint is not IPEndPoint)
  61. return;
  62. connection = new((IPEndPoint)_tcpClient.Client.LocalEndPoint, (IPEndPoint)_tcpClient.Client.RemoteEndPoint, null!);
  63. _tcpConnection = connection;
  64. NetworkStream networkStream = _tcpClient.GetStream();
  65. Thread.Sleep(0);
  66. try
  67. {
  68. _bOpen = true;
  69. base.PrevConnector?.Connected(connection);
  70. result = true;
  71. }
  72. finally { allowOpenEvent.Set(); }
  73. for (byte[] buffer = new byte[receiveBufferSize]; ;)
  74. {
  75. int bytesRead = 0;
  76. DateTime receiveTime;
  77. try
  78. {
  79. bytesRead = await networkStream.ReadAsync(buffer);
  80. receiveTime = DateTime.Now;
  81. }
  82. catch
  83. {
  84. break;
  85. }
  86. if (bytesRead <= 0)
  87. break;
  88. byte[] cache = new byte[bytesRead];
  89. Array.Copy(buffer, cache, bytesRead);
  90. Data receivedData = new(cache, connection, receiveTime);
  91. try { base.PrevReceiver?.Receive(receivedData); } catch { }
  92. }
  93. try { _tcpClient?.Close(); } catch { }
  94. try { base.PrevConnector?.Disconnected(connection); } catch { }
  95. _tcpClient = null;
  96. _bOpen = false;
  97. }
  98. catch { }
  99. }, TaskCreationOptions.LongRunning);
  100. }
  101. catch
  102. {
  103. _tcpClient = null;
  104. return false;
  105. }
  106. allowOpenEvent.WaitOne();
  107. tcpConnection = _tcpConnection;
  108. if (result)
  109. return true;
  110. _tcpClient = null;
  111. return false;
  112. }
  113. }
  114. bool ITcpClient.Close()
  115. {
  116. lock (this)
  117. {
  118. if (!_bInitialize)
  119. return false;
  120. if (!_bOpen)
  121. return true;
  122. try { _tcpClient?.Close(); } catch { }
  123. _readTask?.Wait();
  124. _readTask = null;
  125. _bOpen = false;
  126. return true;
  127. }
  128. }
  129. public override bool Send(Data data)
  130. {
  131. if (!_bInitialize)
  132. return false;
  133. if (!_bOpen)
  134. return false;
  135. if (_tcpClient?.Connected != true)
  136. return false;
  137. if (data.RawData is null || data.RawData.Length == 0)
  138. return false;
  139. try
  140. {
  141. NetworkStream networkStream = _tcpClient!.GetStream();
  142. networkStream.Write([.. data.RawData], 0, data.RawData.Length);
  143. networkStream.Flush();
  144. data.DateTime = DateTime.Now;
  145. }
  146. catch
  147. {
  148. return false;
  149. }
  150. return true;
  151. }
  152. void IDisposable.Dispose()
  153. {
  154. (this as ITcpClient).Close();
  155. }
  156. }