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

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?

Thanks in advanced.

解决方案

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值