org.eclipse.paho.client.mqttv3 示例代码
时间: 2023-07-15 14:12:56 浏览: 91
org.eclipse.paho.client.mqttv3-1.2.5-jar
以下是一个简单的使用 Eclipse Paho MQTT Java 客户端库的示例代码:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttClientExample {
public static void main(String[] args) {
String broker = "tcp://mqtt.eclipseprojects.io:1883";
String clientId = "JavaMqttClient";
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");
String topic = "test/topic";
int qos = 1;
mqttClient.subscribe(topic, qos);
System.out.println("Subscribed to topic: " + topic);
String message = "Hello, MQTT!";
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(qos);
mqttClient.publish(topic, mqttMessage);
System.out.println("Message published");
mqttClient.disconnect();
System.out.println("Disconnected");
} catch (MqttException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
```
这个例子创建一个 MQTT 客户端连接到公共 MQTT 代理(broker),然后订阅一个主题并发布一条消息。在这个例子中,我们使用了 Eclipse Paho MQTT Java 客户端库的 `MqttClient` 类。您需要在构造函数中指定代理的 URL、客户端 ID 和持久化方式。然后,您需要创建一个 `MqttConnectOptions` 对象来设置连接选项,例如“清除会话”(clean session)选项。在这个例子中,我们订阅了一个主题并发布了一条消息。我们还调用了 `disconnect()` 方法来断开连接。
阅读全文