MQTT应用程序使用单个客户端应用程序/库与两个代理连接

问题描述:

我正在使用MQTT Eclipse Paho Java库(JAR)连接到MQTT代理。MQTT应用程序使用单个客户端应用程序/库与两个代理连接

但我想使用相同的库连接两个代理。我已经实现了与两个代理连接的代码,它确实连接了,但问题在于某些时候连接随机断开连接(任一连接)。

那么使用一个MQTT客户端库连接两个MQTT代理的最佳方式是什么?

更新

我的连接代码看起来如下:

import org.eclipse.paho.client.mqttv3.MqttClient; 
Class com.test.A 
{ 
    MqttClient mMqttClient; 
    A() 
    { 
     mMqttClient = new MqttClient("broker_url_1", "Client1", persistence); 

     // Create MQTT connection options 
     MqttConnectOptions connOpts = new MqttConnectOptions(); 
     connOpts.setCleanSession(true); // Create new clear session 

     mMqttClient.connect(connOpts); 
    } 
} 

import org.eclipse.paho.client.mqttv3.MqttClient; 
Class com.test.B 
{ 
    MqttClient mMqttClient; 
    B() 
    { 
     mMqttClient = new MqttClient("broker_url_2", "Client2", persistence); 

     // Create MQTT connection options 
     MqttConnectOptions connOpts = new MqttConnectOptions(); 
     connOpts.setCleanSession(true); // Create new clear session 

     mMqttClient.connect(connOpts); 
    }  
} 

错误,我连接大量后得到connectionLost: cause: Connection lost

+0

让我们看看你使用的代码,并从经纪人/客户端的任何错误消息,当他们断开 – hardillb

+0

@hardillb:请检查更新的问题。 – User7723337

+0

这段代码并没有什么帮助,因为这两个客户端在构造函数中都是瞬态变量,所以在初始化之后的某个随机时间将收集对它们的另一个引用。错误也没有那么有用,我会检查经纪人日志,看看他们是否会更快来 – hardillb

要解决失去连接尝试启用自动重新连接功能:

MqttConnectOptions connOpts = new MqttConnectOptions(); 
connOpts.setCleanSession(true); // Create new clear session 
connOpts.setAutomaticReconnect(true); // add this line 

要获得详细的错误信息创建jsr47min.properties文件:

mMqttClient = new MqttClient("broker_url_1", "Client1", persistence); 
Debug debug = mMqttClient.getDebug(); 
debug.dumpClientDebug(); // call at different points in your code? 
+0

MQTT Paho没有'connOpts.setAutomaticReconnect(true);' – User7723337

+0

当然它有[setAutomaticReconnect](https://www.eclipse.org/paho/files/javadoc/org/eclipse/paho/client/mqttv3 /MqttConnectOptions.html)方法 –

+0

版本不匹配我正在使用0.4.0,它在最新版本中。 – User7723337