使用 Java 与 mqttfx 工具,模拟 MQTT 通信
1、引入依赖
<repositories>
<repository>
<id>Eclipse Paho Repo</id>
<url>https://repo.eclipse.org/content/repositories/paho-snapshots/</url>
</repository>
</repositories>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.1</version>
</dependency>
2、Java 代码
package com.example.demo.iot;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.Scanner;
/**
* @author sugarppig
* @date 2023/3/23 17:00
*/
public class MqttTest {
public static void main(String[] args) {
String broker = "tcp://mqtt.eclipseprojects.io:1883"; // MQTT代理的地址
String clientId = "mqtt_java"; // 客户端ID
MemoryPersistence persistence = new MemoryPersistence(); // 设置持久化
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions(); // 设置连接选项
connOpts.setCleanSession(true); // 设置会话清除标志
System.out.println("Connecting to broker: " + broker);
sampleClient.connect(connOpts); // 连接到MQTT代理
System.out.println("Connected");
// 订阅MQTT FX的Topic
String topic = "home/garden/fountain";
int qos = 1;
sampleClient.subscribe(topic, qos);
System.out.println("Subscribed to topic: " + topic);
// 接收来自MQTT FX的消息
sampleClient.setCallback(new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Received message: " + new String(message.getPayload()));
}
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost: " + cause.getMessage());
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {}
});
// 发布消息到MQTT FX的Topic
System.out.println("Publishing message: ");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String content = scanner.nextLine();
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
}
//Thread.sleep(5000); // 等待5秒钟
// 断开连接
//sampleClient.disconnect();
//System.out.println("Disconnected");
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("excep " + me);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、实现效果