MQTT java代码演示

以下是使用Eclipse Paho客户端库的Java代码示例,用于连接到MQTT代理并发布和订阅消息。

首先,需要添加Maven依赖项到项目中:

  
    org.eclipse.paho  
    org.eclipse.paho.client.mqttv3  
    1.2.5  

然后,可以编写Java代码来连接到MQTT代理并发布和订阅消息:

import org.eclipse.paho.client.mqttv3.*;  
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;  
  
public class MqttExample {  
    public static void main(String[] args) {  
        try {  
            // 创建MQTT客户端实例,使用内存存储持久化客户端配置  
            MqttClient client = new MqttClient("tcp://broker.hivemq.com:1883", MqttClient.generateClientId(), new MemoryPersistence());  
  
            // 创建MQTT连接参数,包括用户名和密码(如果需要)  
            MqttConnectOptions options = new MqttConnectOptions();  
            options.setUserName("your_username");  
            options.setPassword("your_password".toCharArray());  
  
            // 连接到MQTT代理  
            client.connect(options);  
  
            // 发布消息到主题“test/topic”  
            String payload = "Hello, MQTT!";  
            MqttMessage message = new MqttMessage(payload.getBytes());  
            message.setQos(2); // 设置服务质量为2(确保传递)  
            client.publish("test/topic", message);  
  
            // 订阅主题“test/topic”,并在接收到消息时打印消息内容和发布时间戳  
            client.subscribe("test/topic", new IMqttMessageListener() {  
                @Override  
                public void messageArrived(String topic, MqttMessage message) throws Exception {  
                    System.out.println("Received message: " + new String(message.getPayload()) + " at " + message.getTimestamp());  
                }  
            });  
        } catch (MqttException e) {  
            e.printStackTrace();  
        }  
    }  
}

你可能感兴趣的:(java,python,开发语言)