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

107 строки
4.2 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core.Adapter;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System.Linq;
  9. namespace MQTTnet.Core.Server
  10. {
  11. public sealed class MqttServer : IMqttServer
  12. {
  13. private readonly ILogger<MqttServer> _logger;
  14. private readonly MqttClientSessionsManager _clientSessionsManager;
  15. private readonly ICollection<IMqttServerAdapter> _adapters;
  16. private readonly MqttServerOptions _options;
  17. private CancellationTokenSource _cancellationTokenSource;
  18. public MqttServer(IOptions<MqttServerOptions> options, IEnumerable<IMqttServerAdapter> adapters, ILogger<MqttServer> logger, MqttClientSessionsManager clientSessionsManager)
  19. {
  20. _options = options.Value ?? throw new ArgumentNullException(nameof(options));
  21. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  22. _clientSessionsManager = clientSessionsManager ?? throw new ArgumentNullException(nameof(clientSessionsManager));
  23. if (adapters == null)
  24. {
  25. throw new ArgumentNullException(nameof(adapters));
  26. }
  27. _adapters = adapters.ToList();
  28. _clientSessionsManager.ApplicationMessageReceived += (s, e) => ApplicationMessageReceived?.Invoke(s, e);
  29. _clientSessionsManager.ClientConnected += OnClientConnected;
  30. _clientSessionsManager.ClientDisconnected += OnClientDisconnected;
  31. }
  32. public IList<ConnectedMqttClient> GetConnectedClients()
  33. {
  34. return _clientSessionsManager.GetConnectedClients();
  35. }
  36. public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
  37. public event EventHandler<MqttClientDisconnectedEventArgs> ClientDisconnected;
  38. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  39. public void Publish(MqttApplicationMessage applicationMessage)
  40. {
  41. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  42. _options.ApplicationMessageInterceptor?.Invoke(applicationMessage);
  43. _clientSessionsManager.DispatchApplicationMessage(null, applicationMessage);
  44. }
  45. public async Task StartAsync()
  46. {
  47. if (_cancellationTokenSource != null) throw new InvalidOperationException("The MQTT server is already started.");
  48. _cancellationTokenSource = new CancellationTokenSource();
  49. await _clientSessionsManager.RetainedMessagesManager.LoadMessagesAsync();
  50. foreach (var adapter in _adapters)
  51. {
  52. adapter.ClientAccepted += OnClientAccepted;
  53. await adapter.StartAsync(_options);
  54. }
  55. _logger.LogInformation("Started.");
  56. }
  57. public async Task StopAsync()
  58. {
  59. _cancellationTokenSource?.Cancel(false);
  60. _cancellationTokenSource?.Dispose();
  61. _cancellationTokenSource = null;
  62. foreach (var adapter in _adapters)
  63. {
  64. adapter.ClientAccepted -= OnClientAccepted;
  65. await adapter.StopAsync();
  66. }
  67. _clientSessionsManager.Clear();
  68. _logger.LogInformation("Stopped.");
  69. }
  70. private void OnClientAccepted(object sender, MqttServerAdapterClientAcceptedEventArgs eventArgs)
  71. {
  72. eventArgs.SessionTask = Task.Run(async () => await _clientSessionsManager.RunClientSessionAsync(eventArgs.Client), _cancellationTokenSource.Token);
  73. }
  74. private void OnClientConnected(object sender, MqttClientConnectedEventArgs eventArgs)
  75. {
  76. _logger.LogInformation("Client '{0}': Connected.", eventArgs.Client.ClientId);
  77. ClientConnected?.Invoke(this, eventArgs);
  78. }
  79. private void OnClientDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
  80. {
  81. _logger.LogInformation("Client '{0}': Disconnected.", eventArgs.Client.ClientId);
  82. ClientDisconnected?.Invoke(this, eventArgs);
  83. }
  84. }
  85. }