我正在使用JAVA paho
客户端和mosquitto mqtt broker 1.6.7。
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.2</version>
</dependency>
我要订阅多个主题,所以我创建了一个类似于以下内容的类:
private String topic = "";
private MqttClient client = null;
public MqttEndpoint(String topic) throws InterruptedException {
this.topic = topic;
new Thread() {
@Override
public void run() {
try {
client = getNewClient();
client.setCallback(new Callback());
client.subscribe(topic);
//isInitialized=true;
} catch (MqttException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
我在主类中的代码如下:
new MqttEndpoint("abc/def");
new MqttEndpoint("abc/def2");
...
我为连接创建了线程,以避免长连接时间。我的问题:通过这种方法,我(并非总是,但有时)会出现连接丢失错误(32109):
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:190)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.io.EOFException
at java.base/java.io.DataInputStream.readByte(DataInputStream.java:272)
at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:92)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:137)
... 1 more
getNewClient
仅返回一个新客户端:
public static MqttClient getNewClient(){
MqttClient client = null;
try {
String id=MqttClient.generateClientId();
client = new MqttClient("tcp://localhost", id,new MemoryPersistence() );
MqttConnectOptions options = new MqttConnectOptions();
options.setMaxInflight(8000);
options.setAutomaticReconnect(true);
client.connect(options);
} catch (MqttException exception) {
if (exception.getCause() instanceof InterruptedException) {
throw (InterruptedException) exception.getCause();
}
}
return client;
}
如果我删除线程,我没有收到此错误:
public MqttEndpoint(String topic) throws InterruptedException {
this.topic = topic;
try {
client = getNewClient();
client.setCallback(new Callback());
client.subscribe(topic);
LOGGER.info("subscribed to "+ topic);
//isInitialized=true;
} catch (MqttException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我怎么了?
编辑: 我正在使用QoS 1发布消息
答案 0 :(得分:0)
问题是以下几行:
String id=MqttClient.generateClientId();
我根据用户名和系统时间生成一个客户端ID。如果同时创建多个客户端,则ID冲突的可能性会大大增加,这将导致连接丢失错误。...