mqtt服务器搭建

更新源:sudo apt update

安装mqtt服务器:sudo apt install mosquitto

mqtt服务器配置

sudo nano /etc/mosquitto/mosquitto.conf//修改配置文件,添加如下配置拒绝匿名访问

pid_file /run/mosquitto/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d
allow_anonymous false//不允许匿名访问
password_file /etc/mosquitto/pwfile.example//设置用户名密码存放的文件

设置mqtt服务器的用户密码

mosquitto_passwd -c /etc/mosquitto/pwfile.example zsl//表示用户为zsl,用户密码存放在etc/mosquitto/pwfile.example -c表示清空etc/mosquitto/pwfile.example里面的信息,然后再将用户添加进去,不加-c将在etc/mosquitto/pwfile.example文件末尾一直追加

查看mqtt服务状态如遇见Unit quitto.service could not be found提示信息则查看mqtt服务文件是否创建

sudo ls /lib/systemd/system/mosquitto.service
sudo ls /etc/systemd/system/mosquitto.service

 如果没有创建则可以创建一个简单的服务文件

sudo nano /etc/systemd/system/mosquitto.service

添加如下内容:
[Unit]
Description=Mosquitto MQTT Broker
Documentation=man:mosquitto.conf(5) man:mosquitto(8)
After=network.target

[Service]
ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
Restart=on-failure
User=mosquitto
Group=mosquitto

[Install]
WantedBy=multi-user.target

重新加载systemd配置,使新的服务文件生效
sudo systemctl daemon-reload
查看服务器是否已经启动
sudo systemctl status mosquitto

查看mqtt启动失败的日志信息sudo tail -f /var/log/mosquitto/mosquitto.log


客户端安装

sudo apt install mosquitto-clients

订阅消息

mosquitto_sub -h "127.0.0.1" -p 1883 -u zsl -P zsl -t "hello"
//-h "127.0.0.1"指定服务器的IP地址 -p 1833 端口 -u zsl 用户 -P zsl 密码 -t "hello"订阅的主题名称

服务端向客户端发消息

mosquitto_pub -h "127.0.0.1" -p 1883 -u zsl -P zsl -t "helo" -m "nihao"

qt mqtt服务器搭建

下载qt/mqtt库GitHub - qt/qtmqtt at 6.5.3然后修改CMakeLists.txt如下

# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: BSD-3-Clause


set(CMAKE_PREFIX_PATH "D:\Qt\6.5.3\mingw_64")#替换为自己的路径

cmake_minimum_required(VERSION 3.16)

include(.cmake.conf)
project(QtMqtt
    VERSION "${QT_REPO_MODULE_VERSION}"
    DESCRIPTION "Qt Mqtt Libraries"
    HOMEPAGE_URL "https://qt.io/"
    LANGUAGES CXX C
)
set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Build type" FORCE)
find_package(Qt6 ${PROJECT_VERSION} CONFIG REQUIRED COMPONENTS BuildInternals Core Network)
find_package(Qt6 ${PROJECT_VERSION} CONFIG OPTIONAL_COMPONENTS Quick WebSockets # For tests
                                                               Gui Widgets) # For examples
qt_internal_project_setup()

qt_build_repo()

使用qt打开CMakeLists.txt,选择mingw套件编译生成,

1、生成完之后,将C:\Users\www23\Desktop\1\qtmqtt-6.5.3\src\mqtt目录下的所有.h文件拷贝到D:\Qt\6.5.3\mingw_64\include\QtMqtt。qt安装目录下,

2、将C:\Users\www23\Desktop\1\qtmqtt-6.5.3\build\Desktop_Qt_6_5_3_MinGW_64_bit-Debug\include\QtMqtt所有的.h文件也拷贝过去,

3、将C:\Users\www23\Desktop\1\qtmqtt-6.5.3\build\Desktop_Qt_6_5_3_MinGW_64_bit-Debug\bin目录下的.dll文件拷贝到安装路径下-bin

4、将C:\Users\www23\Desktop\1\qtmqtt-6.5.3\build\Desktop_Qt_6_5_3_MinGW_64_bit-Debug\lib目录下的.a文件也拷贝到qt安装目录下-lib

5、在项目工程.pro文件写添加:

LIBS+=C:\Users\www23\Desktop\1\qtmqtt-6.5.3\build\Desktop_Qt_6_5_3_MinGW_64_bit-Debug\lib\libQt6Mqtt.a

如果遇见QSslSocket cannot 则可以将OPENSSL库下载下来,将libeay32.dllhe ssleay32.dll拷贝到项目的build目录下。

windows下安装mqtt服务器

地址:https://mosquitto.org/download/

添加环境变量//D:\Program Files\mosquitto//重启电脑生效

添加用户认证信息与linux一致,唯一需要注意的是,需要在路径名上添加双引号,mosquitto_passwd -c "D:\Program Files\mosquitto\pwfile.example" zsl

启动mosquitto:net start mosquitto//需要管理员身份运行

停止mosquitto:net stop mosquitto

查看当前所有服务的状态:net start

简单示例

发布:
QMqttClient client;
    client.setHostname("127.0.0.1");  // 指定MQTT服务器地址
    client.setPort(1883);             // 指定MQTT服务器端口
    client.setUsername("zsl");        // 指定用户名
    client.setPassword("zsl");        // 指定密码

    QObject::connect(&client, &QMqttClient::connected, [&client]() {
        qDebug() << "Connected to MQTT broker.";

        // 发布消息到主题 "hello"
        auto result = client.publish(QMqttTopicName("hello"), "这是一条测试消息");

        if (result == -1) {
            qDebug() << "Failed to publish message.";
        } else {
            qDebug() << "Message published.";
        }
    });

    QObject::connect(&client, &QMqttClient::disconnected, []() {
        qDebug() << "Disconnected from MQTT broker.";
    });

    QObject::connect(&client, &QMqttClient::errorChanged, [](QMqttClient::ClientError error) {
        qDebug() << "MQTT Client Error:" << error;
    });

    client.connectToHost();
订阅:
QMqttClient client;
    client.setHostname("127.0.0.1");  // 指定MQTT服务器地址
    client.setPort(1883);             // 指定MQTT服务器端口
    client.setUsername("zsl");        // 指定用户名
    client.setPassword("zsl");        // 指定密码

    QObject::connect(&client, &QMqttClient::connected, [&client]() {
        qDebug() << "Connected to MQTT broker.";

        // 订阅主题 "hello"
        QMqttSubscription *subscription = client.subscribe("hello");

        if (!subscription) {
            qDebug() << "Failed to subscribe.";
        } else {
            qDebug() << "Subscribed to topic 'hello'.";
        }

        QObject::connect(subscription, &QMqttSubscription::messageReceived, [](const QMqttMessage &message) {
            qDebug() << "Received message on topic" << message.topic() << ":" << message.payload();
        });
    });

    QObject::connect(&client, &QMqttClient::disconnected, []() {
        qDebug() << "Disconnected from MQTT broker.";
    });

    QObject::connect(&client, &QMqttClient::errorChanged, [](QMqttClient::ClientError error) {
        qDebug() << "MQTT Client Error:" << error;
    });

    client.connectToHost();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mangosteeny

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值