Java Eclipse Paho Implementation - Auto reconnect

Black Glix picture Black Glix · Nov 16, 2015 · Viewed 12.7k times · Source

I'm trying to implement eclipse.paho in my project to connect Mqtt Broker (Both subscribing and publishing purpose). The problem is, when I using the subscribing feature (Implementing MqttCallback interface), I couldn't figure our how can I reconnect if the connection lost. MqttCallback interface has a connectionLost method, but it is useful for the debug what causes the connection lost. I searched but couldn't find a way to establish auto reconnect. Can you suggest a way or document about this problem?

Answer

hardillb picture hardillb · Nov 16, 2015

The best way to do this is to structure your connection logic so it lives in a method on it's own so it can be called again from the connectionLost callback in the MqttCallback instance.

The connectionLost method is passed a Throwable that will be the exception that triggered the disconnect so you can make decisions about the root cause and how this may effect when/how you reconnect.

The connection method should connect and subscribe to the topics you require.

Something like this:

public class PubSub {

  MqttClient client;
  String topics[] = ["foo/#", "bar"];
  MqttCallback callback = new MqttCallback() {
    public void connectionLost(Throwable t) {
      this.connect();
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
      System.out.println("topic - " + topic + ": " + new String(message.getPayload()));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
    }
  };

  public static void main(String args[]) {
    PubSub foo = new PubSub();
  }

  public PubSub(){
    this.connect();
  }

  public void connect(){
    client = new MqttClient("mqtt://localhost", "pubsub-1");
    client.setCallback(callback);
    client.connect();
    client.subscribe(topics);
  }

}