MQTT 客户端连接丢失在重新连接到代理后不起作用
MQTT client connectionLost do not work after reconnect to broker
我是 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()
触发器在我第二次重新启动代理时不起作用。
我该如何解决?
非常感谢。
如果您使用 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");
}
对我有用的是使用 Mqttclient.reconnect()
。
我是 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()
触发器在我第二次重新启动代理时不起作用。
我该如何解决?
非常感谢。
如果您使用 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");
}
对我有用的是使用 Mqttclient.reconnect()
。