提供一个简单的Eclipse Paho MQTT的客户端代码
时间: 2024-03-21 18:42:02 浏览: 62
基于Eclipse paho的MQTT java客户端
好的,以下是一个简单的 Eclipse Paho MQTT 客户端代码,用于连接到 MQTT 代理并发布消息:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MQTTClient {
public static void main(String[] args) {
String topic = "test/topic";
String content = "Hello, World!";
int qos = 2;
String broker = "tcp://mqtt.eclipse.org:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient mqttClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: " + broker);
mqttClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: " + content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
mqttClient.publish(topic, message);
System.out.println("Message published");
mqttClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} 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);
me.printStackTrace();
}
}
}
```
这个客户端连接到 Eclipse 的公共 MQTT 测试代理,并发布一条消息到 "test/topic" 主题。你可以根据你的实际需求进行修改。
阅读全文