MQTT的简单应用

1. 添加依赖

pom.xml中添加Eclipse Paho MQTT库的依赖项:

<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.5</version>
</dependency>

2. 创建MQTT客户端类 

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttExample {

    private static final String BROKER_URL = "tcp://broker.hivemq.com:1883"; // 公共MQTT Broker
    private static final String CLIENT_ID = "JavaClient";
    private static final String TOPIC = "test/topic";

    private MqttClient client;
    private MqttConnectOptions connOpts;

    public MqttExample() {
        try {
            // 创建MqttClient实例
            client = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence());

            // 设置连接选项
            connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true); // 是否清除会话
            connOpts.setAutomaticReconnect(true); // 自动重连
            connOpts.setConnectionTimeout(10); // 连接超时时间
            connOpts.setKeepAliveInterval(20); // 心跳间隔时间

            // 设置回调函数
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost: " + cause.getMessage());
                    // 当连接丢失时触发
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Message received on topic " + topic + ":\n\t" + new String(message.getPayload()));
                    // 当消息到达时触发
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("Delivery complete: " + token.isComplete());
                    // 当消息传递完成时触发
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void connect() {
        try {
            // 连接到MQTT Broker
            client.connect(connOpts);
            System.out.println("Connected to broker: " + BROKER_URL);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void subscribe(String topic) {
        try {
            client.subscribe(topic);
            System.out.println("Subscribed to topic: " + topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void publish(String topic, String content, int qos) {
        try {
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos); // 设置QoS级别
            client.publish(topic, message);
            System.out.println("Message published on topic " + topic + ": " + content);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            client.disconnect();
            System.out.println("Disconnected from broker");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MqttExample example = new MqttExample();

        // 连接到Broker
        example.connect();

        // 订阅主题
        example.subscribe(TOPIC);

        // 发布消息
        example.publish(TOPIC, "Hello MQTT!", 1);

        // 模拟长时间运行,等待消息到来
        try {
            Thread.sleep(30000); // 保持连接30秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 断开连接
        example.disconnect();
    }
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿时光不负.

爱意随风起,风止意难平。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值