Java Eclipse Paho Implementation - Auto reconnect

后端 未结 3 489
不知归路
不知归路 2021-01-05 01:41

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 subscribi

3条回答
  •  庸人自扰
    2021-01-05 02:27

    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);
      }
    
    }
    

提交回复
热议问题