MQTT 订阅主体的 JAVA
时间: 2024-05-24 13:08:38 浏览: 14
MQTT 是一种轻量级的消息传递协议,它被广泛应用于物联网、移动设备等领域。Java 中有多个 MQTT 客户端库可以使用,其中 Eclipse Paho 是比较流行的一个。订阅 MQTT 主题可以使用 Paho 提供的 MqttClient 类。以下是 Java 中使用 Paho 订阅 MQTT 主题的示例代码:
```
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class Subscriber {
public static void main(String[] args) {
String broker = "tcp://localhost:1883";
String clientId = "JavaSubscriber";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient client = new MqttClient(broker, clientId, persistence);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost: " + cause.getMessage());
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Received message from topic " + topic + ": " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Message delivered to broker");
}
});
client.connect();
client.subscribe("myTopic");
} catch (MqttException e) {
System.out.println("Error subscribing to topic: " + e.getMessage());
}
}
}
```
这段代码通过创建一个 MqttClient 实例来连接到 MQTT 代理,并使用 setCallback 方法设置消息回调函数。在回调函数中,可以处理接收到的消息。使用 subscribe 方法来订阅主题。如果订阅成功,当代理收到与该主题匹配的消息时,将调用回调函数来处理该消息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)