Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

MqttTcpServerAdapter.cs 6.8 KiB

7 лет назад
7 лет назад
7 лет назад
6 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
6 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
6 лет назад
7 лет назад
6 лет назад
7 лет назад
7 лет назад
6 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
7 лет назад
6 лет назад
7 лет назад
7 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #if NET452 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
  2. using System;
  3. using System.Net;
  4. using System.Net.Security;
  5. using System.Net.Sockets;
  6. using System.Security.Authentication;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MQTTnet.Adapter;
  11. using MQTTnet.Diagnostics;
  12. using MQTTnet.Serializer;
  13. using MQTTnet.Server;
  14. namespace MQTTnet.Implementations
  15. {
  16. public class MqttTcpServerAdapter : IMqttServerAdapter
  17. {
  18. private readonly IMqttNetChildLogger _logger;
  19. private CancellationTokenSource _cancellationTokenSource;
  20. private Socket _defaultEndpointSocket;
  21. private Socket _tlsEndpointSocket;
  22. private X509Certificate2 _tlsCertificate;
  23. public MqttTcpServerAdapter(IMqttNetChildLogger logger)
  24. {
  25. if (logger == null) throw new ArgumentNullException(nameof(logger));
  26. _logger = logger.CreateChildLogger(nameof(MqttTcpServerAdapter));
  27. }
  28. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  29. public Task StartAsync(IMqttServerOptions options)
  30. {
  31. if (_cancellationTokenSource != null) throw new InvalidOperationException("Server is already started.");
  32. _cancellationTokenSource = new CancellationTokenSource();
  33. if (options.DefaultEndpointOptions.IsEnabled)
  34. {
  35. _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
  36. _defaultEndpointSocket.Bind(new IPEndPoint(options.DefaultEndpointOptions.BoundIPAddress, options.GetDefaultEndpointPort()));
  37. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  38. Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token),
  39. _cancellationTokenSource.Token);
  40. }
  41. if (options.TlsEndpointOptions.IsEnabled)
  42. {
  43. if (options.TlsEndpointOptions.Certificate == null)
  44. {
  45. throw new ArgumentException("TLS certificate is not set.");
  46. }
  47. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  48. if (!_tlsCertificate.HasPrivateKey)
  49. {
  50. throw new InvalidOperationException("The certificate for TLS encryption must contain the private key.");
  51. }
  52. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  53. _tlsEndpointSocket.Bind(new IPEndPoint(options.TlsEndpointOptions.BoundIPAddress, options.GetTlsEndpointPort()));
  54. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  55. Task.Run(
  56. () => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token),
  57. _cancellationTokenSource.Token);
  58. }
  59. return Task.FromResult(0);
  60. }
  61. public Task StopAsync()
  62. {
  63. _cancellationTokenSource?.Cancel(false);
  64. _cancellationTokenSource?.Dispose();
  65. _cancellationTokenSource = null;
  66. _defaultEndpointSocket?.Dispose();
  67. _defaultEndpointSocket = null;
  68. _tlsCertificate = null;
  69. _tlsEndpointSocket?.Dispose();
  70. _tlsEndpointSocket = null;
  71. return Task.FromResult(0);
  72. }
  73. public void Dispose()
  74. {
  75. StopAsync().GetAwaiter().GetResult();
  76. }
  77. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  78. {
  79. while (!cancellationToken.IsCancellationRequested)
  80. {
  81. try
  82. {
  83. //todo: else branch can be used with min dependency NET46
  84. #if NET452 || NET461
  85. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null).ConfigureAwait(false);
  86. #else
  87. var clientSocket = await _defaultEndpointSocket.AcceptAsync().ConfigureAwait(false);
  88. #endif
  89. clientSocket.NoDelay = true;
  90. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, null), new MqttPacketSerializer(), _logger);
  91. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  92. }
  93. catch (ObjectDisposedException)
  94. {
  95. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  96. }
  97. catch (Exception exception)
  98. {
  99. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  100. {
  101. return;
  102. }
  103. _logger.Error(exception, "Error while accepting connection at default endpoint.");
  104. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  105. }
  106. }
  107. }
  108. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  109. {
  110. while (!cancellationToken.IsCancellationRequested)
  111. {
  112. try
  113. {
  114. #if NET452 || NET461
  115. var clientSocket = await Task.Factory.FromAsync(_tlsEndpointSocket.BeginAccept, _tlsEndpointSocket.EndAccept, null).ConfigureAwait(false);
  116. #else
  117. var clientSocket = await _tlsEndpointSocket.AcceptAsync().ConfigureAwait(false);
  118. #endif
  119. var sslStream = new SslStream(new NetworkStream(clientSocket));
  120. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false).ConfigureAwait(false);
  121. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(clientSocket, sslStream), new MqttPacketSerializer(), _logger);
  122. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  123. }
  124. catch (ObjectDisposedException)
  125. {
  126. // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed.
  127. }
  128. catch (Exception exception)
  129. {
  130. if (exception is SocketException s && s.SocketErrorCode == SocketError.OperationAborted)
  131. {
  132. return;
  133. }
  134. _logger.Error(exception, "Error while accepting connection at TLS endpoint.");
  135. await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
  136. }
  137. }
  138. }
  139. }
  140. }
  141. #endif