如何使用java编写MQTT的客户端和服务端
时间: 2023-05-18 21:05:47 浏览: 126
JAVA MQTT客户端模拟代码
5星 · 资源好评率100%
您可以使用 Eclipse Paho 提供的 Java 客户端库来编写 MQTT 客户端和服务端。以下是使用 Eclipse Paho 的示例代码:
客户端:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttClientSample {
public static void main(String[] args) {
String broker = "tcp://localhost: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");
String topic = "test";
String content = "Hello World";
int qos = 2;
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 e) {
System.out.println("Reason: " + e.getReasonCode());
System.out.println("Message: " + e.getMessage());
System.out.println("Loc: " + e.getLocalizedMessage());
System.out.println("Cause: " + e.getCause());
System.out.println("Excep: " + e);
e.printStackTrace();
}
}
}
```
服务端:
```java
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttServerSample {
public static void main(String[] args) {
String broker = "tcp://localhost:1883";
String clientId = "JavaServer";
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");
mqttClient.setCallback(new MqttCallback() {
public void connectionLost(Throwable cause) {
System.out.println("Connection lost");
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message received: " + new String(message.getPayload()));
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery complete");
}
});
mqttClient.subscribe("test");
System.out.println("Subscribed to topic: test");
while (true) {
// do nothing
}
} catch (MqttException e) {
System.out.println("Reason: " + e.getReasonCode());
System.out.println("Message: " + e.getMessage());
System.out.println("Loc: " + e.getLocalizedMessage());
System.out.println("Cause: " + e.getCause());
System.out.println("Excep: " + e);
e.printStackTrace();
}
}
}
```
阅读全文