Java Eclipse Paho实现 - 自动重新连接

时间:2015-11-16 12:12:38

标签: java eclipse mqtt paho

我试图在我的项目中实现public void OnPointerDown (PointerEventData eventData) { btn_pressed = true; } public void OnPointerUp (PointerEventData eventData) { btn_pressed = false; } if(btn_pressed) { //code { 以连接Mqtt Broker(订阅和发布目的)。问题是,当我使用订阅功能(实现eclipse.paho接口)时,我无法确定如果连接丢失,我该如何重新连接。 MqttCallback接口有一个connectionLost方法,但它对于导致连接丢失的调试很有用。我搜索但无法找到建立自动重新连接的方法。你能建议一个关于这个问题的方法或文件吗?

3 个答案:

答案 0 :(得分:7)

执行此操作的最佳方法是构建连接逻辑,使其位于自己的方法中,以便可以从connectionLost实例中的MqttCallback回调中再次调用它。

connectionLost方法传递一个Throwable,它将触发断开连接,因此您可以决定根本原因以及这可能会影响您重新连接的时间/方式。

连接方法应该连接并订阅您需要的主题。

这样的事情:

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

}

答案 1 :(得分:2)

要使用自动重新连接,只需在setAutomaticReconnect(true)对象上设置MqttConnectOptions

MqttAndroidClient mqttClient = new MqttAndroidClient(context, mqttUrl, clientId);

MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);

mqttClient.connect(mqttConnectOptions, null, mqttActionListener());

答案 2 :(得分:1)

我正在使用paho客户端1.2.0。 借助MqttClient.setAutomaticReconnect(true)和接口MqttCallbackExtended API,感谢https://github.com/eclipse/paho.mqtt.java/issues/493,当与代理的连接断开时,我可以设法自动重新连接。

请参见下面的代码。

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

    }
}