MQTT Disconnect and Reconnects at very short intervals for Android Client

I’m trying to connect mqtt broker with fixed clientID, it’s working fine but with several reconnect client disconnect and reconnect at very short intervals. Initializing connection from Android service onCreate and cleanup in onDestroy method.

//client builder
MqttClientBuilder builder = MqttClient.builder()
.identifier(identifier)
.serverHost(brokerAddress)
.serverPort(port)
.addDisconnectedListener(new MqttClientDisconnectedListener() {
@Override
public void onDisconnected(@NotNull MqttClientDisconnectedContext context) {
Log.e(“hive”,"disconnected " + context.getSource().toString());
context.getCause().printStackTrace();
}
})
.addConnectedListener(new MqttClientConnectedListener() {
@Override
public void onConnected(@NotNull MqttClientConnectedContext context) {
Log.e(“hive”,“connected”);
}
})
.automaticReconnectWithDefaultConfig();

client = builder
        .useMqttVersion3()
        .buildBlocking();
1 Like

I am seeing this as well, my reconnect interval is 5 seconds and I get a disconnect every 5 seconds and an immediate reconnect.

Hi asmenter15,

Welcome to out community forum, we are glad to see your interest in MQTT and HiveMQ!

You indicated that “my reconnect interval is 5 seconds and I get a disconnect every 5 seconds and an immediate reconnect”.

Question: Are you using a unique Client Id for you MQTT Client (this is the string you pass to the identifier() method)?

To get a better advise please feel free to provide an example of your source code.

Kind regards,
Dasha from HiveMQ Team

So I saw the unique clientId elsewhere and this did lead me to what I think my issue is, which is actually an instance issue where I have multiple instances of my class that are subscribing with a single clientId so I think each instance is kicking the other instance off when it does it’s own connection flow.

Out of curiosity, when you connect again with the same clientId, do we expect it to kick the existing connection with that clientId? Or will it be rejected since that clientId is already used?

Thank you for the quick response!

Hey asmenter,

the broker must disconnect the previously connected client when a successful new connect with the same clientId occurs. This mechanism is called “client take-over”.

Kind regards,
Finn