【C++】开源:MQTT安装与配置使用

这篇具有很好参考价值的文章主要介绍了【C++】开源:MQTT安装与配置使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

😏★,°:.☆( ̄▽ ̄)/$:.°★ 😏
这篇文章主要介绍MQTT安装与配置使用。
学其所用,用其所学。——梁启超
欢迎来到我的博客,一起学习知识,共同进步。
喜欢的朋友可以关注一下,下次更新不迷路🥞

😏1. MQTT介绍

官网:https://mqtt.org/

MQTT是一个基于客户端-服务器消息发布/订阅传输协议

MQTT (Message Queuing Telemetry Transport) 是一种轻量级的消息传输协议,通常用于物联网设备和应用程序之间进行通信。它是基于发布/订阅模式设计的,其中消息发布者将消息发布到特定主题(Topic),然后订阅该主题的客户端将收到这些消息。MQTT 特别适合在网络带宽有限的情况下进行通信,因为它使用的数据包非常小。此外,它还提供了多种 QoS (Quality of Service) 级别来确保消息的可靠性和有效性。

MQTT 协议具有以下特点:

1.轻量级:相对于 HTTP 等协议,MQTT 的数据包非常小,因此能够以较低的网络带宽进行通信。
2.发布/订阅模式:通过订阅一个特定的主题,客户端能够接收和处理与该主题相关的所有消息。
3.多种 QoS 级别:MQTT 提供了三种不同的 QoS级别,以满足不同场景下的需求。
4.可扩展性:MQTT 的设计使得它能够方便地扩展到大规模系统中,并支持多种不同的连接方式,例如TCP、WebSocket 等。

MQTT数据包结构如下:

固定头(Fixed header),存在于所有MQTT数据包中,表示数据包类型及数据包的分组类标识;
可变头(Variable header),存在于部分MQTT数据包中,数据包类型决定了可变头是否存在及其具体内容;
消息体(Payload),存在于部分MQTT数据包中,表示客户端收到的具体内容;

MQTT 支持三种不同级别的服务质量(Quality of Service,QoS),分别为 QoS0、QoS1 和 QoS2

QoS0:最多发送一次,消息发送者只会将消息发布出去,但是并不保证接收者是否成功接收到该消息。这是最低级别的服务质量,也是最简单和最快速的传输方式。
QoS1:至少发送一次,消息发送者确保至少将消息传输给接收者一次。如果接收者没有确认消息或者确认消息失败,则消息发送者会尝试重新发送,直到接收者成功地接收到消息为止。
QoS2:恰好发送一次,消息发送者确保接收者恰好只能收到一次消息。在该级别下,消息发送者和接收者会进行两轮握手确认,以保证消息的可靠性和有效性。

选择哪种服务质量级别取决于应用场景和对通信安全性的要求。需要注意的是,在选择高级别的服务质量时,会增加通信延迟和网络带宽的消耗。

目前mqtt的代理平台有:Mosquitto、VerneMQ、EMQTT、Eclipse Paho等。

😊2. 环境安装

Github:https://github.com/eclipse/mosquitto

下面在Ubuntu安装Mosquitto来体验mqtt的消息传递过程:

sudo apt-get install mosquitto	# 服务端
sudo apt install mosquitto-clients	# 客户端
sudo apt-get install libmosquitto-dev # 开发依赖包
g++ -o main main.cpp -lmosquitto && ./main # g++

启动/关闭mqtt服务:

mosquitto -v	# 启用所有日志记录类型
# 启动和关闭服务
sudo service mosquitto start
sudo service mosquitto stop
# 查看运行状态
sudo systemctl status mosquitto
# 查看帮助
mosquitto --help
#查看运行进程号:
ps -aux | grep mosquitto
#执行命令杀死进程:
kill -9 进程号

MQTT消息传输测试:

1、启动代理服务:mosquitto -v  # -v 详细模式 打印调试信息(启动一次就好)
2、订阅主题:mosquitto_sub -t 'test/topic' -v
3、发布内容:mosquitto_pub -t 'test/topic' -m 'hello world'

MQTT在线测试工具:https://mqttx.app/zh

😆3. Mosquitto示例

MQTT发布订阅示例:

#include <mosquitto.h>
#include <iostream>
#include <cstring>

// MQTT消息回调函数
void message_callback(struct mosquitto* mosq, void* userdata, const struct mosquitto_message* message)
{
    std::cout << "Received message: " << (char*)message->payload << std::endl;
}

int main()
{
    struct mosquitto* mosq = nullptr;
    const char* host = "localhost";
    int port = 1883;
    const char* topic = "test/topic";
    const char* message = "Hello, MQTT!";
    int keepalive = 60;
    bool clean_session = true;

    // 初始化mosquitto库
    mosquitto_lib_init();

    // 创建MQTT客户端
    mosq = mosquitto_new(NULL, clean_session, NULL);
    if (!mosq)
    {
        std::cerr << "Failed to create MQTT client" << std::endl;
        return -1;
    }

    // 设置消息回调函数
    mosquitto_message_callback_set(mosq, message_callback);

    // 连接到MQTT代理
    if (mosquitto_connect(mosq, host, port, keepalive) != MOSQ_ERR_SUCCESS)
    {
        std::cerr << "MQTT connection failed" << std::endl;
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return -1;
    }

    // 订阅主题
    if (mosquitto_subscribe(mosq, NULL, topic, 0) != MOSQ_ERR_SUCCESS)
    {
        std::cerr << "Failed to subscribe to topic" << std::endl;
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return -1;
    }

    // 发布消息
    if (mosquitto_publish(mosq, NULL, topic, strlen(message), message, 0, false) != MOSQ_ERR_SUCCESS)
    {
        std::cerr << "Failed to publish message" << std::endl;
        mosquitto_destroy(mosq);
        mosquitto_lib_cleanup();
        return -1;
    }

    // 循环处理MQTT消息
    while (mosquitto_loop(mosq, -1, 1) == MOSQ_ERR_SUCCESS) {}

    // 断开MQTT连接和清理资源
    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    return 0;
}

MQTT发布订阅C++风格,封装为函数编译调用示例:

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <mosquitto.h>
#include <string>

const std::string MQTT_BROKER_ADDRESS = "localhost";  // Mosquitto broker 的地址
const int MQTT_BROKER_PORT = 1883;  // Mosquitto broker 的端口号

// Mosquitto库初始化
void mosquittoInit(struct mosquitto*& mosq) {
    mosquitto_lib_init();
    mosq = mosquitto_new("mosq_cpp_example", true, nullptr);
    if (!mosq) {
        std::cerr << "Error: Unable to initialize Mosquitto library." << std::endl;
        exit(EXIT_FAILURE);
    }
}

// 连接到Mosquitto broker
void mosquittoConnect(struct mosquitto* mosq) {
    int ret = mosquitto_connect(mosq, MQTT_BROKER_ADDRESS.c_str(), MQTT_BROKER_PORT, 60);
    if (ret != MOSQ_ERR_SUCCESS) {
        std::cerr << "Error: Unable to connect to Mosquitto broker. Return code: " << ret << std::endl;
        exit(EXIT_FAILURE);
    }
}

// 发布消息到指定主题
void mosquittoPublish(struct mosquitto* mosq, const std::string& topic, const std::string& message) {
    int ret = mosquitto_publish(mosq, nullptr, topic.c_str(), message.size(), message.c_str(), 0, false);
    if (ret != MOSQ_ERR_SUCCESS) {
        std::cerr << "Error: Unable to publish message. Return code: " << ret << std::endl;
    }
}

// 订阅指定主题
void mosquittoSubscribe(struct mosquitto* mosq, const std::string& topic) {
    int ret = mosquitto_subscribe(mosq, nullptr, topic.c_str(), 0);
    if (ret != MOSQ_ERR_SUCCESS) {
        std::cerr << "Error: Unable to subscribe to topic. Return code: " << ret << std::endl;
    }
}

// 回调函数处理接收到的消息
void onMessage(struct mosquitto* mosq, void* userdata, const struct mosquitto_message* message) {
    std::string receivedMessage((char*)message->payload, message->payloadlen); // char* -> string
    std::cout << "Received message on topic: " << message->topic << ", Message: " << receivedMessage << std::endl;
}

int main() {
    struct mosquitto* mosq = nullptr;

    mosquittoInit(mosq);
    mosquittoConnect(mosq);

    // 订阅主题
    mosquittoSubscribe(mosq, "test");

    // 发布主题
    while (true) {
        mosquittoPublish(mosq, "test", "Hello, Mosquitto!");
        std::cout << "Published message." << std::endl;
        usleep(1000 * 1000);
    }
    
    // 设置消息接收回调函数
    mosquitto_message_callback_set(mosq, onMessage);

    // 循环处理消息
    mosquitto_loop_forever(mosq, -1, 1);

    // 断开连接并清理资源
    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    return 0;
}

基于MQTT的机器人项目示例:

项目Github地址:https://github.com/horo2016/easyMQOS

这个项目用MQTT代替我们常用的ROS,来对机器人的各个节点进行实现,webjs网页来控制,可以学习。

c++ mqtt,c++开源项目学习,网络,tcp/ip,mqtt

以上。文章来源地址https://www.toymoban.com/news/detail-755462.html

到了这里,关于【C++】开源:MQTT安装与配置使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【MQTT】MQTT简介+安装+使用 python MQTT客户端

    目录 前言 MQTT 协议简介 为何选择 MQTT MQTT 通讯运作方式 MQTT 协议帧格式 MQTT服务器搭建和使用  公共MQTT 测试服务器 MQTT服务器搭建 各种MQTT代理服务程序比较 Mosquitto安装 MQTT使用方法 测试MQTT服务器 程序中使用MQTT 本文随时更新,转载请注明出处,源地址:http://t.csdn.cn/kCC0B 文

    2024年02月01日
    浏览(30)
  • 【MQTT】使用MQTT在Spring Boot项目中实现异步消息通信

    前置文章: (一)MQTT协议与指令下发;MQTT与Kafka比较 (二)用MQTT在Spring Boot项目中实现异步消息通信 MQTT(Message Queuing Telemetry Transport)是一种轻量级的、开放的消息协议,特别适用于物联网设备之间的通信。本篇文章将介绍如何在Spring Boot项目中使用MQTT来实现异步消息通信

    2024年01月17日
    浏览(41)
  • 基于STM32+ESP8266+FreeRTOS+安卓App上位机+MQTT连接OneNET的智能家居项目(软件开源篇附百度网盘链接)

      本篇文章主要是分享智能家居项目中的下位机STM32+FreeRTOS的代码部分。以下是项目最终的效果 stm32 esp8266 语音控制智能家居_哔哩哔哩_bilibili   另外附上main函数中的部分代码,完整代码会在文章末尾放上百度网盘链接,可以自行下载。 链接:https://pan.baidu.com/s/1IS-OMLy2_pyWyM

    2024年02月08日
    浏览(31)
  • 【opencv C++版本】安装和学习 ==Windows下使用VSCode配置OpenCV开发环境

    ref:https://opencv.org/releases/ ref:https://www.cnblogs.com/ticlab/p/16817542.html c_cpp_properties.json 照着ref 没安装成功,先写个二分查找把 ref:https://docs.opencv.org/4.x/df/d65/tutorial_table_of_content_introduction.html nnd,用这个ref在ubuntu20.04 上安装成功了!!!咳咳咳 ref:https://blog.csdn.net/weixin_4479667

    2024年02月14日
    浏览(41)
  • HomeAssistant快速使用教程二:安装mqtt,作为消息服务器

    因为要接入很多DIY的硬件,因为语言,接口的不同,所以使用MQTT协议进行它们之间的通信。 在这里使用emqx的MQTT,因为他们还有一个配套前端,比较好用。 这里放上官方github连接:emqx官网连接 官方文档支持中文,可以自己查阅,进行更加灵活的配置安装(源码安装),因为这

    2024年02月11日
    浏览(36)
  • 【C++】开源:CGAL计算几何库配置使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍CGAL计算几何库配置使用。 无专精则不能成,无涉猎则不能通。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 项目Github地址: https://github.com/CGAL/cgal CGAL(Computational G

    2024年02月13日
    浏览(30)
  • 【C++】开源:Muduo网络库配置与使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍Muduo网络库配置与使用。 无专精则不能成,无涉猎则不能通。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 项目Github地址: https://github.com/chenshuo/muduo Muduo 是一个基于

    2024年02月15日
    浏览(25)
  • 【C++】开源:Boost库常用组件配置使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍Boost库常用组件配置使用。 无专精则不能成,无涉猎则不能通。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 项目Github地址: https://github.com/boostorg/boost Boost库在线书籍

    2024年02月15日
    浏览(38)
  • 【C++】开源:websocketpp安装与使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍websocketpp的安装与使用。 学其所用,用其所学。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,它使得客户端和

    2024年02月14日
    浏览(26)
  • 【C++】开源:Boost网络库Asio配置使用

    😏 ★,° :.☆( ̄▽ ̄)/$: .°★ 😏 这篇文章主要介绍Asio网络库配置使用。 无专精则不能成,无涉猎则不能通。——梁启超 欢迎来到我的博客,一起学习,共同进步。 喜欢的朋友可以关注一下,下次更新不迷路🥞 项目Github地址: https://github.com/boostorg/asio Boost.Asio 是一个用于

    2024年02月15日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包