【问题标题】:MQTT client connectionLost do not work after reconnect to broker重新连接到代理后,MQTT 客户端连接丢失不起作用
【发布时间】:2018-12-13 10:56:20
【问题描述】:

我是 MQTT 的新手。当客户端失去连接时,我尝试重新连接到代理。这是我的功能:

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

这是重新连接的功能:

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

在代理重新启动的第一次工作正常。但是,这个connectionLost() 触发器在我第二次重新启动代理时不起作用。 我该如何解决?
非常感谢。

【问题讨论】:

    标签: java mqtt broker


    【解决方案1】:

    对我有用的是使用Mqttclient.reconnect()

    【讨论】:

      【解决方案2】:

      如果您使用this mqtt client,则无需额外代码即可自动重新连接

      您可以在创建MqttClient 时在MqttConnectOptions 中指定重新连接和清理会话选项。

      示例代码:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-10
        • 2013-10-06
        • 1970-01-01
        相关资源
        最近更新 更多