Java Eclipse Paho Implementation - Auto reconnect

后端 未结 3 464
不知归路
不知归路 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:14

    I'm using the paho client 1.2.0. With the MqttClient.setAutomaticReconnect(true) and interface MqttCallbackExtended API, and thanks to https://github.com/eclipse/paho.mqtt.java/issues/493, I could manage to reconnect automatically when the connection to broker is down.

    See below the code.

    //Use the MqttCallbackExtended to (re-)subscribe when method connectComplete is invoked
    public class MyMqttClient implements MqttCallbackExtended {
        private static final Logger logger = LoggerFactory.getLogger(MqttClientTerni.class);
        private final int qos = 0;
        private String topic = "mytopic";
        private MqttClient client;
    
        public MyMqttClient() throws MqttException {
            String host = "tcp://localhost:1883";
            String clientId = "MQTT-Client";
    
            MqttConnectOptions conOpt = new MqttConnectOptions();
            conOpt.setCleanSession(true);
            //Pay attention here to automatic reconnect
        conOpt.setAutomaticReconnect(true);
            this.client = new org.eclipse.paho.client.mqttv3.MqttClient(host, clientId);
            this.client.setCallback(this);
            this.client.connect(conOpt);
        }
    
        /**
         * @see MqttCallback#connectionLost(Throwable)
         */
        public void connectionLost(Throwable cause) {
            logger.error("Connection lost because: " + cause);
    
    
        /**
         * @see MqttCallback#deliveryComplete(IMqttDeliveryToken)
         */
        public void deliveryComplete(IMqttDeliveryToken token) {
        }
    
        /**
         * @see MqttCallback#messageArrived(String, MqttMessage)
         */
        public void messageArrived(String topic, MqttMessage message) throws MqttException {
            logger.info(String.format("[%s] %s", topic, new String(message.getPayload())));
        }
    
        public static void main(String[] args) throws MqttException, URISyntaxException {
            MyMqttClient s = new MyMqttClient();
        }
    
        @Override
        public void connectComplete(boolean arg0, String arg1) {
            try {
          //Very important to resubcribe to the topic after the connection was (re-)estabslished. 
          //Otherwise you are reconnected but you don't get any message
            this.client.subscribe(this.topic, qos);
            } catch (MqttException e) {
                e.printStackTrace();
            }
    
        }
    }
    

提交回复
热议问题