Skip to content

Commit

Permalink
Fix NullReferenceException when calling Ping (#1834)
Browse files Browse the repository at this point in the history
* Check connection status before doing ping

* Fix broken reconnect sample

* Update ReleaseNotes.md
  • Loading branch information
chkr1011 authored Sep 6, 2023
1 parent e2e7aac commit cae7206
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ReleaseNotes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [Client] Fixed NullReferenceExeption when performing a Ping when the client is not connected (#1831).
3 changes: 3 additions & 0 deletions Samples/Client/Client_Connection_Samples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,9 @@ public static void Reconnect_Using_Timer()
}
}
});

Console.WriteLine("Press <Enter> to exit");
Console.ReadLine();
}
}
}
9 changes: 7 additions & 2 deletions Source/MQTTnet/Client/MqttClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MqttPingRespPacket>(MqttPingReqPacket.Instance, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -441,7 +446,7 @@ async Task<MqttClientConnectResult> 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)
{
Expand Down Expand Up @@ -513,7 +518,7 @@ async Task<MqttClientConnectResult> 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();
Expand Down

0 comments on commit cae7206

Please sign in to comment.