当前位置: 首页 > java >正文

【C/C++】MQTT

文章目录

  • MQTT 协议
    • 1 基本概念
    • 2 核心特性
    • 3 核心组件
    • 4 C++ 简易实现(基于 Paho MQTT 库)
      • 环境准备
      • 示例代码
    • 不同mqtt对比
      • 关键差异说明

MQTT 协议

1 基本概念

MQTT(Message Queuing Telemetry Transport)是一种轻量级的发布/订阅模式消息传输协议,专为低带宽、高延迟或不稳定的网络环境设计,广泛应用于物联网(IoT)场景。

官方定义

MQTT is a Client Server publish/subscribe messaging transport protocol.
It is light weight, open, simple, and designed to be easy to implement.
These characteristics make it ideal for use in many situations, including constrained environments such as for communication in Machine to Machine (M2M) and Internet of Things (IoT) contexts where a small code footprint is required and/or network bandwidth is at a premium.

The protocol runs over TCP/IP, or over other network protocols that provide ordered, lossless, bi-directional connections. Its features include:

  • Use of the publish/subscribe message pattern which provides one-to-many message distribution and decoupling of applications.

  • A messaging transport that is agnostic to the content of the payload.

  • Three qualities of service for message delivery:

    • “At most once”, where messages are delivered according to the best efforts of the operating environment. Message loss can occur. This level could be used, for example, with ambient sensor data where it does not matter if an individual reading is lost as the next one will be published soon after.
    • “At least once”, where messages are assured to arrive but duplicates can occur.
    • “Exactly once”, where messages are assured to arrive exactly once. This level could be used, for example, with billing systems where duplicate or lost messages could lead to incorrect charges being applied.
  • A small transport overhead and protocol exchanges minimized to reduce network traffic.

  • A mechanism to notify interested parties when an abnormal disconnection occurs.

2 核心特性

  • 轻量高效:报文头部最小仅2字节。
  • 发布/订阅模型:解耦消息生产者(Publisher)和消费者(Subscriber)。
  • QoS支持:提供3种消息传输质量等级:
    • QoS 0:最多一次(可能丢包)。
    • QoS 1:至少一次(确保送达,可能重复)。
    • QoS 2:精确一次(复杂握手保证唯一性)。
  • 低功耗:适合嵌入式设备。
  • 基于TCP/IP:默认端口1883(未加密)、8883(SSL加密)。

3 核心组件

  • Broker:消息代理服务器,负责消息路由和转发。
  • Client:设备或应用程序,可发布或订阅消息。
  • Topic:分层消息主题(如 sensors/temperature)。

4 C++ 简易实现(基于 Paho MQTT 库)

环境准备

  1. 安装 Mosquitto Broker
    sudo apt-get install mosquitto mosquitto-clients
    
  2. 安装 Paho MQTT C++ 库
# c++库的依赖
git clone https://github.com/eclipse/paho.mqtt.c.git
cd paho.mqtt.c
cmake -B build -DPAHO_WITH_SSL=ON
cmake --build build
sudo cmake --install build --prefix /usr/local# C++库
git clone https://github.com/eclipse/paho.mqtt.cpp
cd paho.mqtt.cpp
cmake -B build -DPAHO_MQTT_C_LIBRARIES=/usr/local/lib/libpaho-mqtt3as.so
cmake --build build
sudo cmake --install build --prefix /usr/local

示例代码

  1. 发布者(Publisher)
#include <mqtt/client.h>
#include <iostream>const std::string BROKER_ADDRESS = "tcp://localhost:1883";
const std::string CLIENT_ID = "paho_cpp_publisher";
const std::string TOPIC = "test/topic";int main() {mqtt::client client(BROKER_ADDRESS, CLIENT_ID);try {// 连接到 Brokerclient.connect();std::cout << "Connected to broker!" << std::endl;// 发布消息std::string payload = "Hello MQTT!";auto msg = mqtt::make_message(TOPIC, payload);client.publish(msg);std::cout << "Message published: " << payload << std::endl;// 断开连接client.disconnect();}catch (const mqtt::exception& exc) {std::cerr << "Error: " << exc.what() << std::endl;return 1;}return 0;
}
  1. 订阅者(Subscriber)
#include <mqtt/client.h>
#include <iostream>
#include <cstdlib>const std::string BROKER_ADDRESS = "tcp://localhost:1883";
const std::string CLIENT_ID = "paho_cpp_subscriber";
const std::string TOPIC = "test/topic";class callback : public mqtt::callback {
public:void message_arrived(mqtt::const_message_ptr msg) override {std::cout << "Message received: " << msg->get_payload()<< " on topic: " << msg->get_topic() << std::endl;}
};int main() {mqtt::client client(BROKER_ADDRESS, CLIENT_ID);callback cb;client.set_callback(cb);try {// 连接到 Brokerclient.connect();client.subscribe(TOPIC);std::cout << "Subscribed to topic: " << TOPIC << std::endl;// 保持运行以接收消息while (true) {std::this_thread::sleep_for(std::chrono::seconds(1));}client.disconnect();}catch (const mqtt::exception& exc) {std::cerr << "Error: " << exc.what() << std::endl;return 1;}return 0;
}
  1. 编译与运行
  • 编译命令(使用 g++):
    g++ publisher.cpp -o publisher -lpaho-mqttpp3 -lpaho-mqtt3as
    g++ subscriber.cpp -o subscriber -lpaho-mqttpp3 -lpaho-mqtt3as
    
  • 运行步骤:
    • 启动 Broker(Mosquitto默认已后台运行)。
    • 启动订阅者:./subscriber
    • 启动发布者:./publisher

  1. 关键点解析
  • QoS 设置:在 publishsubscribe 时可通过参数指定 QoS 等级。
  • 异步通信:Paho 库支持异步回调机制(如 message_arrived)。
  • 遗嘱消息(Last Will):可在连接时设置遗嘱消息,用于客户端异常断线通知。

通过此实现,您已掌握 MQTT 的核心通信流程。实际项目中可根据需求扩展消息持久化、SSL加密等功能。

不同mqtt对比

关键差异说明

特性Paho MQTT C++ 库Mosquitto C 库
编程风格面向对象(C++封装)面向过程(C语言接口)
安装复杂度较高(需手动编译依赖)简单(直接 apt 安装)
功能扩展性更丰富的异步回调机制基础功能
文档支持官方文档详细社区示例较多

推荐选择:

  • 如果需高性能和异步特性,优先选择 Paho MQTT C++ 库
  • 如果快速验证或简单项目,直接使用 Mosquitto C 库
http://www.xdnf.cn/news/3678.html

相关文章:

  • Git从入门到精通-第三章-获取Git仓库
  • 【Agent搭建】利用coze平台搭建一个AI销售?
  • Spring MVC @RequestBody 注解怎么用?接收什么格式的数据?
  • 重载和覆写有什么区别?
  • 18、状态库:中央魔法仓库——React 19 Zustand集成
  • STM32基础教程——软件I2C
  • 力扣-字符串-165 比较版本号
  • 【算法基础】递归算法 - JAVA
  • C++ STL vector容器详解:从原理到实践
  • Python绘制地球的重力地图
  • <servlet-class>和</url-pattern>的作用
  • Oracle VirtualBox 在 Windows 上的详细安装步骤
  • AnimateCC教学:照片旋转飞舞并爆炸....
  • NV189NV195美光固态闪存NV197NV199
  • 什么是“原子变量”?
  • 【vscode】.dart文件没有错误波浪线
  • Dubbo(93)如何在电商系统中应用Dubbo?
  • Power Query精通指南4:M语言(查询结构与值系统)、查询优化、自动刷新
  • rails 8 CSS不起效问题解决
  • 异步数据库事务锁:电商库存扣减的防超卖秘籍
  • 【Linux系统篇】:Linux线程控制基础---线程的创建,等待与终止
  • Tesla的战略变化策略(2010~2024)以及给中国汽车厂家的启发
  • Deformable DETR模型解读(附源码+论文)
  • 【算法基础】快速排序算法 - JAVA
  • Cycleresearcher:通过自动化评审改进自动化研究
  • Python 数据智能实战 (10):智能商品推荐 - LLM “猜你喜欢”
  • v0.6.7/OllamaSetup.exe下载链接
  • SpringSecurity配置(权限认证)
  • 论数据分片技术及其应用
  • 市面上所有大模型apikey获取指南(持续更新中)