gpt4 book ai didi

java - 如何使用 Paho 驱动程序重新连接到 MQTT

转载 作者:太空宇宙 更新时间:2023-11-04 12:41:27 26 4
gpt4 key购买 nike

我正在为我的一些应用程序使用 MQTT 客户端 Java 库,并且我认为我正在以错误的方式重新连接到代理。现在我有一个类来处理 MQTT 操作,例如连接、断开连接、发布和订阅。

public class MqttConnection {

private static final String BROKER_ADDRESS = Preferences.getProperty("mqtt-address");
private static final String BROKER_PORT = Preferences.getProperty("mqtt-port");
private static final String BROKER_URI = "tcp://" + BROKER_ADDRESS + ":" + BROKER_PORT;

private static final String VHOST = Preferences.getProperty("mqtt-vhost");
private static final String USERNAME = Preferences.getProperty("mqtt-username");
private static final String PASSWORD = Preferences.getProperty("mqtt-password");

private static MqttClient client;

private static final Logger logger = LogManager.getLogger(MqttConnection.class);

static {
try {
client = new MqttClient(BROKER_URI, MqttClient.generateClientId());
} catch (MqttException ex) {
logger.fatal(ex);
}
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable thrwbl) {
logger.info("MQTT : Perte de connexion...");
MqttConnection.start();
}

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// CODE HERE
}

@Override
public void deliveryComplete(IMqttDeliveryToken imdt) { }
});
}

public static void start() {
connect();
}

private static void connect() {
if (!client.isConnected()) {
try {
if (Preferences.getProperty("mqtt-isauth").equalsIgnoreCase("true")) {
MqttConnectOptions options = new MqttConnectOptions();
String username = (VHOST.equals("")) ? USERNAME : VHOST + ":" + USERNAME;
options.setUserName(username);
options.setPassword(PASSWORD.toCharArray());
client.connect(options);
} else {
client.connect();
}
logger.info("MQTT : Connecté au broker.");
} catch (MqttException ex) {
logger.fatal(ex);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
logger.fatal(e);
}
connect();
}
}
}

private static void subscribe() {
if (client.isConnected()) {
try {
client.subscribe("+/SWI1");
} catch (MqttException e) {
logger.fatal(e);
}
}
}
}

但是当它尝试重新连接时似乎会打开许多​​连接,并使代理出现错误。重新连接到 MQTT 代理的最佳方式是什么?

最佳答案

您可以使用MqttConnectOptions.setAutomaticReconnect(true)启用自动重新连接。

关于java - 如何使用 Paho 驱动程序重新连接到 MQTT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com