Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

MqttServerAdapter.cs 4.8 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using System;
  2. using System.Net;
  3. using System.Net.Security;
  4. using System.Net.Sockets;
  5. using System.Security.Authentication;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MQTTnet.Core.Adapter;
  10. using MQTTnet.Core.Diagnostics;
  11. using MQTTnet.Core.Serializer;
  12. using MQTTnet.Core.Server;
  13. namespace MQTTnet.Implementations
  14. {
  15. public class MqttServerAdapter : IMqttServerAdapter, IDisposable
  16. {
  17. private CancellationTokenSource _cancellationTokenSource;
  18. private Socket _defaultEndpointSocket;
  19. private Socket _tlsEndpointSocket;
  20. private X509Certificate2 _tlsCertificate;
  21. private bool _isRunning;
  22. public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
  23. public void Start(MqttServerOptions options)
  24. {
  25. if (options == null) throw new ArgumentNullException(nameof(options));
  26. if (_isRunning) throw new InvalidOperationException("Server is already started.");
  27. _isRunning = true;
  28. _cancellationTokenSource = new CancellationTokenSource();
  29. if (options.DefaultEndpointOptions.IsEnabled)
  30. {
  31. _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  32. _defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
  33. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  34. Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  35. }
  36. if (options.TlsEndpointOptions.IsEnabled)
  37. {
  38. if (options.TlsEndpointOptions.Certificate == null)
  39. {
  40. throw new ArgumentException("TLS certificate is not set.");
  41. }
  42. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  43. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  44. _tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
  45. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  46. Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  47. }
  48. }
  49. public void Stop()
  50. {
  51. _isRunning = false;
  52. _cancellationTokenSource?.Dispose();
  53. _cancellationTokenSource = null;
  54. _defaultEndpointSocket?.Dispose();
  55. _defaultEndpointSocket = null;
  56. _tlsEndpointSocket?.Dispose();
  57. _tlsEndpointSocket = null;
  58. }
  59. public void Dispose()
  60. {
  61. Stop();
  62. }
  63. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  64. {
  65. while (!cancellationToken.IsCancellationRequested)
  66. {
  67. try
  68. {
  69. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null);
  70. var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, null), new DefaultMqttV311PacketSerializer());
  71. ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
  72. }
  73. catch (Exception exception)
  74. {
  75. MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while acceping connection at default endpoint.");
  76. }
  77. }
  78. }
  79. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  80. {
  81. while (!cancellationToken.IsCancellationRequested)
  82. {
  83. try
  84. {
  85. var clientSocket = await Task.Factory.FromAsync(_defaultEndpointSocket.BeginAccept, _defaultEndpointSocket.EndAccept, null);
  86. var sslStream = new SslStream(new NetworkStream(clientSocket));
  87. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false);
  88. var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream), new DefaultMqttV311PacketSerializer());
  89. ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
  90. }
  91. catch (Exception exception)
  92. {
  93. MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while acceping connection at TLS endpoint.");
  94. }
  95. }
  96. }
  97. }
  98. }