javamqttbroker

MQTT client connectionLost do not work after reconnect to broker


I'm newbie in MQTT. I try to reconnect to broker when the client lost connection. This is my function:

@Override
public void connectionLost(Throwable cause) {
    // TODO Auto-generated method stub
    reconnectStatus = 0;

    executor.scheduleAtFixedRate(reconnectRunnable, 0, 5, TimeUnit.SECONDS); // reconnect every 5s

    System.out.println(cause);
}

And this is function to reconnect:

// reconnect to the broker
Runnable reconnectRunnable = new Runnable() {
    public void run() {
       if(reconnectStatus == 1) {
           System.out.println("Stop runnable!");
           executor.shutdown();
           return;
       } else {
           init();
       }
    }
};

It's working fine at the firs time when broker restart. However, this connectionLost() trigger does not work at the second time I restart the broker. How can I fix it?
Thank you very much.


Solution

  • No need for extra code for automatic reconnect if you use this mqtt client

    You can specify reconnect and clean session option in MqttConnectOptions while creating MqttClient.

    Sample code:

    public void initClinet(){
        MqttClient client=new MqttClient("server address", MqttClient.generateClientId());
        client.setCallback(new MyListener());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setUserName("username");
        options.setPassword("password".toCharArray());
        options.setKeepAliveInterval(10);
        options.setCleanSession(false);
        client.connect(options);
        client.subscribe("channelname");    
    }