MqttClient.PublishAsync(...) throws exception with message "The client is not connected.", but MqttClient.IsConnected returns true.
Task<MQTTnet.Client.Publishing.MqttClientPublishResult> Task = MqttClient.PublishAsync( TopicName, MessageBuilder.Build(), MqttQualityOfServiceLevel.AtLeastOnce );
await Task;
if (Task.Result.ReasonCode != MQTTnet.Client.Publishing.MqttClientPublishReasonCode.Success)
PutDebugLogEntry( DebugLogEntry.Debug( DEBUG_LOGS_TAG, $"Unsuccesfull publish to topic \"{TopicName }\" with code {Task.Result.ReasonCode}" ) );
throw new OperationCanceledException( $"Unsuccesfull async publish to topic \"{TopicName }\" with code {Task.Result.ReasonCode}" );
Similar to that has also happened to me while calling MqttClient.DisconnectAsync().
I'm currently having random Internet disconnects. It also happends when debugging (stepping) the application while the client is connected.
I'm using MqttNet version 3.0.9-rc1 for net46.
Thanks a lot in advance.
Maybe the message is a little bit misleading. This can happen when the client is going to be disconnected. This will return "IsConnected" true but throws the exception. Pending disconnects are not part of the "IsConnected" property. I will consider to add this value here as well.
Also please keep in mind that there is no "IsConnected" state at all. We never know if the client is still connected. From TCP perspective we only know that the other end is down if we send and get no ACK or a keep alive ping failed. So in the end you only know that you are still connected if the last transmission of data has succeeded.
I'm using the IsConected property as part of my checks to know whether I can or can't publish from the client.
Tracing the stack with the debugger, the TCP connection was already in a closed state, and IsConnected continued being true for more than ten minutes until I paused for debugging.
If, from your point of view, there is a more robust or correct way for doing this, please, let me know and I'll follow your advice.
Thanks a lot for your work!
In my opinion there is nothing you can do. You need to catch those exceptions and try again it if fails. The thing is that there is no information if the state is connected or not. Even if I expose the ping methods for the client and you perform a ping and pong before you publish it might fail if the connection was lots a few ms after the ping reply.