MQTT 客户端连接丢失在重新连接到代理后不起作用



我是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()触发器在我第二次重新启动代理时不起作用。 我该如何解决它?
谢谢。

如果您使用此 MQTT 客户端,则无需额外的代码即可自动重新连接

您可以在创建MqttClientMqttConnectOptions中指定重新连接和清理会话选项。

示例代码:

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().

最新更新