java开发MQTT客户端服务端
时间: 2023-09-04 14:06:31 浏览: 119
Java开发MQTT客户端服务端需要使用MQTT协议的Java库,例如Eclipse Paho或者Mosquitto等。以下是一个基本的MQTT客户端和服务端的代码示例:
MQTT客户端:
```java
import org.eclipse.paho.client.mqttv3.*;
public class MqttClientExample {
public static void main(String[] args) {
String brokerUrl = "tcp://localhost:1883";
String clientId = "mqtt-client";
String topic = "test/topic";
int qos = 2;
try {
MqttClient mqttClient = new MqttClient(brokerUrl, clientId);
mqttClient.connect();
MqttMessage message = new MqttMessage();
message.setPayload("Hello, MQTT!".getBytes());
message.setQos(qos);
mqttClient.publish(topic, message);
mqttClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
```
MQTT服务端:
```java
import org.eclipse.paho.server.mqttv3.*;
public class MqttServerExample {
public static void main(String[] args) {
int port = 1883;
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttServer mqttServer = new MqttServer(port, persistence);
mqttServer.start();
mqttServer.subscribe("test/topic", (topic, message) -> {
System.out.println("Received message: " + new String(message.getPayload()));
});
Thread.sleep(5000);
mqttServer.stop();
} catch (MqttException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
这个示例使用了Eclipse Paho库来实现MQTT客户端和服务端。MQTT客户端连接到MQTT服务端并发布一条消息,MQTT服务端订阅了该主题并打印出接收到的消息。
阅读全文