使用java编写MQTT客户端和服务端示例
时间: 2023-05-20 21:00:43 浏览: 161
好的,以下是使用Java编写MQTT客户端和服务端示例的代码:
MQTT客户端示例:
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttClientExample {
public static void main(String[] args) {
String topic = "MQTT Examples";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "tcp://iot.eclipse.org:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: " + broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: " + content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("excep " + me);
me.printStackTrace();
}
}
}
MQTT服务端示例:
import org.eclipse.paho.server.mqttv3.*;
import org.eclipse.paho.server.mqttv3.persist.MemoryPersistence;
public class MqttServerExample {
public static void main(String[] args) {
int qos = 2;
String broker = "tcp://iot.eclipse.org:1883";
String clientId = "JavaServer";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttServerPersistence serverPersistence = new MemoryPersistence();
MqttServer server = new MqttServer(broker, clientId, serverPersistence);
server.start();
System.out.println("Server started");
MqttServerMessageHandler handler = new MqttServerMessageHandler() {
@Override
public void handleMessage(String topic, MqttMessage message) throws Exception {
System.out.println("Received message: " + message.toString() + " on topic: " + topic);
}
};
server.subscribe("MQTT Examples", qos, handler);
System.out.println("Subscribed to topic: MQTT Examples");
Thread.sleep(5000);
server.unsubscribe("MQTT Examples");
System.out.println("Unsubscribed from topic: MQTT Examples");
server.stop();
System.out.println("Server stopped");
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("excep " + me);
me.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
希望这些代码能够帮助你!
阅读全文