You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MqttServerAdapter.cs 4.6 KiB

7 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 (_isRunning) throw new InvalidOperationException("Server is already started.");
  26. _isRunning = true;
  27. _cancellationTokenSource = new CancellationTokenSource();
  28. if (options.DefaultEndpointOptions.IsEnabled)
  29. {
  30. _defaultEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  31. _defaultEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetDefaultEndpointPort()));
  32. _defaultEndpointSocket.Listen(options.ConnectionBacklog);
  33. Task.Run(() => AcceptDefaultEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  34. }
  35. if (options.TlsEndpointOptions.IsEnabled)
  36. {
  37. if (options.TlsEndpointOptions.Certificate == null)
  38. {
  39. throw new ArgumentException("TLS certificate is not set.");
  40. }
  41. _tlsCertificate = new X509Certificate2(options.TlsEndpointOptions.Certificate);
  42. _tlsEndpointSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  43. _tlsEndpointSocket.Bind(new IPEndPoint(IPAddress.Any, options.GetTlsEndpointPort()));
  44. _tlsEndpointSocket.Listen(options.ConnectionBacklog);
  45. Task.Run(() => AcceptTlsEndpointConnectionsAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  46. }
  47. }
  48. public void Stop()
  49. {
  50. _isRunning = false;
  51. _cancellationTokenSource?.Dispose();
  52. _cancellationTokenSource = null;
  53. _defaultEndpointSocket?.Dispose();
  54. _defaultEndpointSocket = null;
  55. _tlsEndpointSocket?.Dispose();
  56. _tlsEndpointSocket = null;
  57. }
  58. public void Dispose()
  59. {
  60. Stop();
  61. }
  62. private async Task AcceptDefaultEndpointConnectionsAsync(CancellationToken cancellationToken)
  63. {
  64. while (!cancellationToken.IsCancellationRequested)
  65. {
  66. try
  67. {
  68. var clientSocket = await _defaultEndpointSocket.AcceptAsync();
  69. var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, null), new DefaultMqttV311PacketSerializer());
  70. ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
  71. }
  72. catch (Exception exception)
  73. {
  74. MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while acceping connection at default endpoint.");
  75. }
  76. }
  77. }
  78. private async Task AcceptTlsEndpointConnectionsAsync(CancellationToken cancellationToken)
  79. {
  80. while (!cancellationToken.IsCancellationRequested)
  81. {
  82. try
  83. {
  84. var clientSocket = await _defaultEndpointSocket.AcceptAsync();
  85. var sslStream = new SslStream(new NetworkStream(clientSocket));
  86. await sslStream.AuthenticateAsServerAsync(_tlsCertificate, false, SslProtocols.Tls12, false);
  87. var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(clientSocket, sslStream), new DefaultMqttV311PacketSerializer());
  88. ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(clientSocket.RemoteEndPoint.ToString(), clientAdapter));
  89. }
  90. catch (Exception exception)
  91. {
  92. MqttTrace.Error(nameof(MqttServerAdapter), exception, "Error while acceping connection at TLS endpoint.");
  93. }
  94. }
  95. }
  96. }
  97. }