hivemq / hivemq-mqtt-client

HiveMQ MQTT Client is an MQTT 5.0 and MQTT 3.1.1 compatible and feature-rich high-performance Java client library with different API flavours and backpressure support
https://hivemq.github.io/hivemq-mqtt-client/
Apache License 2.0
847 stars 158 forks source link

No reconnect on user initiated disconnect #525

Closed on-delete closed 2 years ago

on-delete commented 2 years ago

If you do a disconnect on your own, the disconnect will be performed with the source 'user'. In this case, as per the MqttDisconnectHandler, there will be no reconnect initiatet, as it would be in case another source is responsible for the disconnect. Why is it designed in this way, that you have to care about the reconnect (even if you have autoReconnect enabled) in case you do the disconnect on your own? It was a little bit confusing for us, as the expected behaviour was also that the client is responsible for the reconnect in this case.

SgtSilvio commented 2 years ago

Hi @on-delete Sorry for the long delay. When the client would reconnect in any case by default (also on user disconnect), you would never be able to really disconnect the client. It is really simple to achieve a reconnect always/also reconnect on user disconnect

Mqtt5Client.builder()
        ...
        .automaticReconnectWithDefaultConfig()
        .addDisconnectedListener(context -> {
            if (context.getSource() == USER) {
                final MqttClientReconnector reconnector = context.getReconnector();
                final long delay = (long) Math.min(initialDelayNanos * Math.pow(2, reconnector.getAttempts()), maxDelayNanos);
                final long randomDelay = (long) (delay / 4d / Integer.MAX_VALUE * ThreadLocalRandom.current().nextInt());
                reconnector.reconnect(true).delay(delay + randomDelay, TimeUnit.NANOSECONDS);
            }
        })
        ...

I hope this helps. Feel free to comment.

on-delete commented 2 years ago

Hey @SgtSilvio

thanks for the explanation. The problem is not, that we do not know, how to detect a disconnect initiated by a user, but that the expected behaviour was not as the actual one. We expected, that also a user initiated disconnect would cause an automatic reconnect. If thats not the case, it's fine if you have reasons to do so. But that would be something that should be stated in the documentation for example, to avoid irritation about the actual behaviour of the client.

Issue can be closed then.