void TryMaintainConnection(MqttClientConnection connection, DateTime now) { try { if (connection.Status != MqttClientConnectionStatus.Running) { // The connection is already dead or just created so there is no need to check it. return; } if (connection.ConnectPacket.KeepAlivePeriod == 0) { // The keep alive feature is not used by the current connection. return; } if (connection.IsReadingPacket) { // The connection is currently reading a (large) packet. So it is obviously // doing something and thus "connected". return; } // Values described here: [MQTT-3.1.2-24]. // If the client sends 5 sec. the server will allow up to 7.5 seconds. // If the client sends 1 sec. the server will allow up to 1.5 seconds. var maxDurationWithoutPacket = connection.ConnectPacket.KeepAlivePeriod * 1.5D; var secondsWithoutPackage = (now - connection.LastPacketReceivedTimestamp).TotalSeconds; if (secondsWithoutPackage < maxDurationWithoutPacket) { // A packet was received before the timeout is affected. return; } _logger.Warning(null, "Client '{0}': Did not receive any packet or keep alive signal.", connection.ClientId); // Execute the disconnection in background so that the keep alive monitor can continue // with checking other connections. // We do not need to wait for the task so no await is needed. // Also the internal state of the connection must be swapped to "Finalizing" because the // next iteration of the keep alive timer happens. var _ = connection.StopAsync(MqttDisconnectReasonCode.KeepAliveTimeout); } catch (Exception exception) { _logger.Error(exception, "Client {0}: Unhandled exception while checking keep alive timeouts.", connection.ClientId); } }
async Task <MqttClientConnection> CreateClientConnectionAsync(MqttConnectPacket connectPacket, MqttConnectionValidatorContext connectionValidatorContext, IMqttChannelAdapter channelAdapter) { MqttClientConnection connection; MqttClientConnection existingConnection = null; using (await _createConnectionGate.WaitAsync(_cancellationToken).ConfigureAwait(false)) { var session = _sessions.AddOrUpdate( connectPacket.ClientId, key => { _logger.Verbose("Created a new session for client '{0}'.", key); return(new MqttClientSession(key, connectionValidatorContext.SessionItems, _eventDispatcher, _options, _retainedMessagesManager, _rootLogger)); }, (key, existingSession) => { if (connectPacket.CleanSession) { _logger.Verbose("Deleting existing session of client '{0}'.", connectPacket.ClientId); return(new MqttClientSession(key, connectionValidatorContext.SessionItems, _eventDispatcher, _options, _retainedMessagesManager, _rootLogger)); } _logger.Verbose("Reusing existing session of client '{0}'.", connectPacket.ClientId); return(existingSession); }); connection = new MqttClientConnection(connectPacket, channelAdapter, session, connectionValidatorContext, _options, this, _retainedMessagesManager, _rootLogger); _connections.AddOrUpdate( connectPacket.ClientId, key => connection, (key, tempExistingConnection) => { existingConnection = tempExistingConnection; return(connection); }); } // Disconnect the client outside of the lock so that new clients can still connect while a single // one is being disconnected. if (existingConnection != null) { await existingConnection.StopAsync(true).ConfigureAwait(false); } return(connection); }