From 948c7c2b690536742a236cba662b6f7efb43fd2b Mon Sep 17 00:00:00 2001 From: Lucas T Date: Thu, 2 Jan 2025 12:17:05 +0100 Subject: [PATCH] Corrected Cancellation Source for KeepAlive Messages (#2129) * Corrected Cancellation Source for KeepAlive Messages * Use half of the keep alive value for the ping timeout * Update release notes * Update ReleaseNotes.md * Update ReleaseNotes.md * Update ReleaseNotes.md --------- Co-authored-by: christian <6939810+chkr1011@users.noreply.github.com> --- Source/MQTTnet/MqttClient.cs | 12 +++++++----- Source/ReleaseNotes.md | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Source/MQTTnet/MqttClient.cs b/Source/MQTTnet/MqttClient.cs index bb3248ff..9dbe960e 100644 --- a/Source/MQTTnet/MqttClient.cs +++ b/Source/MQTTnet/MqttClient.cs @@ -1041,11 +1041,13 @@ public sealed class MqttClient : Disposable, IMqttClient if (timeWithoutPacketSent > keepAlivePeriod) { - using (var timeoutCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) - { - timeoutCancellationTokenSource.CancelAfter(Options.Timeout); - await PingAsync(timeoutCancellationTokenSource.Token).ConfigureAwait(false); - } + using var pingTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + // We already reached the keep alive timeout. Due to the RFC part [MQTT-3.1.2-24] the server will wait another + // 1/2 of the keep alive time. So we can also use this value as the timeout. + pingTimeout.CancelAfter(keepAlivePeriod / 2); + + await PingAsync(pingTimeout.Token).ConfigureAwait(false); } // Wait a fixed time in all cases. Calculation of the remaining time is complicated diff --git a/Source/ReleaseNotes.md b/Source/ReleaseNotes.md index fd0b1746..5e84863a 100644 --- a/Source/ReleaseNotes.md +++ b/Source/ReleaseNotes.md @@ -13,6 +13,7 @@ * Client: MQTT 5.0.0 is now the default version when connecting with a server **(BREAKING CHANGE)** * Client: Fixed enhanced authentication. * Client: Exposed WebSocket compression options in MQTT client options (thanks to @victornor, #2127) +* Client: Fixed wrong timeout for keep alive check (thanks to @Erw1nT, #2129) * Server: Fixed enhanced authentication. * Server: Set default for "MaxPendingMessagesPerClient" to 1000 **(BREAKING CHANGE)** * Server: Set SSL version to "None" which will let the OS choose the version **(BREAKING CHANGE)**