Java Mqtt 接收消息
时间: 2023-11-15 22:04:10 浏览: 90
QtMqtt - 搭建Mqtt服务,修改QMqtt源码进行消息订阅测试(包含编译成功的库)
Java中可以使用Eclipse Paho客户端库来实现MQTT协议的消息接收。
首先,需要在项目中引入paho-mqtt-client的依赖:
```xml
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
```
然后,可以使用以下代码来实现MQTT消息的接收:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttSubscriber implements MqttCallback {
private MqttClient mqttClient;
public MqttSubscriber() {
try {
String broker = "tcp://localhost:1883";
String clientId = "JavaMqttSubscriber";
MemoryPersistence persistence = new MemoryPersistence();
mqttClient = new MqttClient(broker, clientId, persistence);
mqttClient.setCallback(this);
mqttClient.connect();
mqttClient.subscribe("topic/test");
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable throwable) {
System.out.println("Connection lost!");
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println("Topic: " + topic);
System.out.println("Message: " + new String(mqttMessage.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Delivery complete!");
}
public static void main(String[] args) {
new MqttSubscriber();
}
}
```
在上面的代码中,我们实现了MqttCallback接口,并在构造函数中初始化MqttClient,设置回调函数和订阅主题。在回调函数中,我们可以处理接收到的消息。在main函数中,我们创建了一个MqttSubscriber对象,它会自动连接到MQTT服务器并开始接收消息。
注意:在实际应用中,需要根据实际情况修改broker地址、clientId、订阅的主题等信息。
阅读全文