hivemq / hivemq-mqtt-client-dotnet

The HiveMQ C# Asynchronous MQTT client for .NET featuring full MQTT 5.0 and back pressure support.
https://hivemq.github.io/hivemq-mqtt-client-dotnet/
Apache License 2.0
63 stars 9 forks source link

When the client reconnects, resubscribing will result in duplicate subscriptions #204

Open xuzimianxzm opened 3 weeks ago

xuzimianxzm commented 3 weeks ago

šŸ› Bug Report

šŸ”¬ How To Reproduce

Steps to reproduce the behavior:

When the client reconnects, I try to wait for the automatic disconnection to complete in the Disconnect event, and then try to subscribe again to the topic that was subscribed before the connection was lost. However, duplicate subscriptions will occur at this time, and the number of duplicate subscriptions to the same topic will double after each reconnection. Even if I have explicitly called the Client's unsubscribe topic method, it does not work.

Code sample

The following is the code for restoring topic subscription after automatic reconnection:

 if (sender is not IHiveMQClient client) return;

            logger.LogInformation("The connection has been disconnected. Try to reconnecting");

            while (!client.IsConnected())
            {
                logger.LogInformation("Wait mqtt client auto reconnecting...");
                Thread.Sleep(5000);
            }

            logger.LogInformation("The mqtt client has reconnected.");

            client.UnsubscribeAsync(client.Subscriptions)
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();

            var newsSubscribeResult = client.SubscribeAsync(_subscribeOptions!)
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();

When I consulted the HiveMQClient source code, I found that the subscription topics related information is stored in this variable, as follows:

9079a7730f76d4625313992d9361414

Each time you subscribe, the topics and corresponding handlers that have completed the subscription will be put into this collection:

181b27aa5db5c78c042c2a13f1a3b0d

However, when canceling a subscription, there is no attempt to remove the unsubscribed topics and handlers. You can see that the Subscriptions collection of this HiveMQClient object does not have any call to remove elements:

9079a7730f76d4625313992d9361414

Therefore, based on the above analysis, I took the following temporary corrective measures, that is, manually "Subscriptions.Clear();" to ensure that there will be no repeated subscriptions to Topics: image

pglombardo commented 3 weeks ago

Hi @xuzimianxzm - thanks for letting us know. I'll take a closer look at this and respond back soon!