Java 实现 MQTT 协议收发消息

该文章演示了如何使用Java与EclipsePahoMQTT库连接到MQTT代理,建立客户端并进行消息的订阅与发布。通过MqttClient类创建连接,设置连接选项,然后订阅和发布到特定的Topic,同时实现了消息到达时的回调处理。
摘要由CSDN通过智能技术生成

使用 Java 与 mqttfx 工具,模拟 MQTT 通信

1、引入依赖
    <repositories>
        <repository>
            <id>Eclipse Paho Repo</id>
            <url>https://repo.eclipse.org/content/repositories/paho-snapshots/</url>
        </repository>
    </repositories>
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>1.2.1</version>
    </dependency>
2、Java 代码
package com.example.demo.iot;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.Scanner;

/**
 * @author sugarppig
 * @date 2023/3/23 17:00
 */
public class MqttTest {
    public static void main(String[] args) {
        String broker = "tcp://mqtt.eclipseprojects.io:1883"; // MQTT代理的地址
        String clientId = "mqtt_java"; // 客户端ID
        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); // 连接到MQTT代理
            System.out.println("Connected");


            // 订阅MQTT FX的Topic
            String topic = "home/garden/fountain";
            int qos = 1;
            sampleClient.subscribe(topic, qos);
            System.out.println("Subscribed to topic: " + topic);

            // 接收来自MQTT FX的消息
            sampleClient.setCallback(new MqttCallback() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Received message: " + new String(message.getPayload()));
                }

                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost: " + cause.getMessage());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {}
            });

            // 发布消息到MQTT FX的Topic
            System.out.println("Publishing message: ");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String content = scanner.nextLine();
                MqttMessage message = new MqttMessage(content.getBytes());
                message.setQos(qos);
                sampleClient.publish(topic, message);
            }

            //Thread.sleep(5000); // 等待5秒钟

            // 断开连接
            //sampleClient.disconnect();
            //System.out.println("Disconnected");

        } 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);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
3、实现效果

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值