Java Eclipse Paho实现 - 自动重新连接 [英] Java Eclipse Paho Implementation - Auto reconnect
问题描述
我正在尝试在我的项目中实现 eclipse.paho
,以连接Mqtt Broker(订阅和发布目的)。问题是,当我使用订阅功能(实现 MqttCallback
接口)时,我无法确定如果连接丢失,我该如何重新连接。 MqttCallback接口具有connectionLost方法,但是对于调试造成连接丢失的原因很有用。我搜索,但找不到建立自动重新连接的方法。你能建议一个关于这个问题的方式或文件吗?
感谢高级。
是构建你的连接逻辑,所以它生活在一个自己的方法,所以它可以再次从 connectionLost
回调在 MqttCallback
实例。
connectionLost
方法传递一个Throwable,这将是触发断开连接的异常因此,您可以根据原因做出决定,以及如何重新连接/如何重新连接。
连接方法应该连接并订阅所需的主题。 p>
如下所示:
public class PubSub {
MqttClient客户端;
字符串主题[] = [foo /#,bar];
MqttCallback callback = new MqttCallback(){
public void connectionLost(Throwable t){
this.connect();
}
public void messageArrived(String topic,MqttMessage message)throws异常{
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);
}
}
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 Eclipse Paho实现 - 自动重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!