From cae7206733052918f32b5d7348a63697c149977e Mon Sep 17 00:00:00 2001 From: Christian <6939810+chkr1011@users.noreply.github.com> Date: Wed, 6 Sep 2023 20:08:13 +0200 Subject: [PATCH] Fix NullReferenceException when calling Ping (#1834) * Check connection status before doing ping * Fix broken reconnect sample * Update ReleaseNotes.md --- .github/workflows/ReleaseNotes.md | 1 + Samples/Client/Client_Connection_Samples.cs | 3 +++ Source/MQTTnet/Client/MqttClient.cs | 9 +++++++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ReleaseNotes.md b/.github/workflows/ReleaseNotes.md index e69de29bb..a3c59fc92 100644 --- a/.github/workflows/ReleaseNotes.md +++ b/.github/workflows/ReleaseNotes.md @@ -0,0 +1 @@ +* [Client] Fixed NullReferenceExeption when performing a Ping when the client is not connected (#1831). diff --git a/Samples/Client/Client_Connection_Samples.cs b/Samples/Client/Client_Connection_Samples.cs index 6fca63398..5c1f65112 100644 --- a/Samples/Client/Client_Connection_Samples.cs +++ b/Samples/Client/Client_Connection_Samples.cs @@ -430,6 +430,9 @@ public static void Reconnect_Using_Timer() } } }); + + Console.WriteLine("Press to exit"); + Console.ReadLine(); } } } \ No newline at end of file diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index 02d551f41..a62530643 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -238,6 +238,11 @@ public async Task DisconnectAsync(MqttClientDisconnectOptions options, Cancellat public async Task PingAsync(CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + + ThrowIfDisposed(); + ThrowIfNotConnected(); + if (cancellationToken.CanBeCanceled) { await Request(MqttPingReqPacket.Instance, cancellationToken).ConfigureAwait(false); @@ -441,7 +446,7 @@ async Task Authenticate(IMqttChannelAdapter channelAdap if (receivedPacket is MqttConnAckPacket connAckPacket) { - result = MqttClientResultFactory.ConnectResult.Create(connAckPacket, _adapter.PacketFormatterAdapter.ProtocolVersion); + result = MqttClientResultFactory.ConnectResult.Create(connAckPacket, channelAdapter.PacketFormatterAdapter.ProtocolVersion); } else if (receivedPacket is MqttAuthPacket) { @@ -513,7 +518,7 @@ async Task ConnectInternal(IMqttChannelAdapter channelA using (var effectiveCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken)) { _logger.Verbose("Trying to connect with server '{0}'", Options.ChannelOptions); - await _adapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false); + await channelAdapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false); _logger.Verbose("Connection with server established"); _publishPacketReceiverQueue?.Dispose();