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

java paho,Java Eclipse Paho实现 – 自动重新连接I’mtryingtoimplementeclipse.pahoinmyprojecttoconnectMqttBroker(Bothsubscribingandpublishingpurpose).Theproblemis,whenIusingthesubscribingfeature(ImplementingMqttCallbackint…

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

}

}

今天的文章java paho,Java Eclipse Paho实现 – 自动重新连接分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/7436.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注