public async Task StartAsync(MqttServerOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); if (_cancellationTokenSource != null) { throw new InvalidOperationException("The server is already started."); } _cancellationTokenSource = new CancellationTokenSource(); _retainedMessagesManager = new MqttRetainedMessagesManager(_options, _logger); _clientSessionsManager = new MqttClientSessionsManager(_options, _retainedMessagesManager, _logger); _clientSessionsManager.ApplicationMessageReceived += OnApplicationMessageReceived; _clientSessionsManager.ClientConnected += OnClientConnected; _clientSessionsManager.ClientDisconnected += OnClientDisconnected; await _retainedMessagesManager.LoadMessagesAsync(); foreach (var adapter in _adapters) { adapter.ClientAccepted += OnClientAccepted; await adapter.StartAsync(_options); } _logger.Info <MqttServer>("Started."); Started?.Invoke(this, new MqttServerStartedEventArgs()); }
public async Task StopAsync() { try { if (_cancellationTokenSource == null) { return; } _cancellationTokenSource.Cancel(false); _cancellationTokenSource.Dispose(); foreach (var adapter in _adapters) { adapter.ClientAccepted -= OnClientAccepted; await adapter.StopAsync(); } await _clientSessionsManager.StopAsync(); _logger.Info <MqttServer>("Stopped."); } finally { _cancellationTokenSource = null; _retainedMessagesManager = null; if (_clientSessionsManager != null) { _clientSessionsManager.ApplicationMessageReceived -= OnApplicationMessageReceived; _clientSessionsManager.ClientConnected -= OnClientConnected; _clientSessionsManager.ClientDisconnected -= OnClientDisconnected; } _clientSessionsManager = null; } }
public MqttClientSessionsManager(MqttServerOptions options, MqttRetainedMessagesManager retainedMessagesManager, IMqttNetLogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _options = options ?? throw new ArgumentNullException(nameof(options)); _retainedMessagesManager = retainedMessagesManager ?? throw new ArgumentNullException(nameof(retainedMessagesManager)); }