【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 库)
环境准备
- 安装 Mosquitto Broker:
sudo apt-get install mosquitto mosquitto-clients
- 安装 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
示例代码
- 发布者(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;
}
- 订阅者(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;
}
- 编译与运行
- 编译命令(使用 g++):
g++ publisher.cpp -o publisher -lpaho-mqttpp3 -lpaho-mqtt3as g++ subscriber.cpp -o subscriber -lpaho-mqttpp3 -lpaho-mqtt3as
- 运行步骤:
- 启动 Broker(Mosquitto默认已后台运行)。
- 启动订阅者:
./subscriber
。 - 启动发布者:
./publisher
。
- 关键点解析
- QoS 设置:在
publish
或subscribe
时可通过参数指定 QoS 等级。 - 异步通信:Paho 库支持异步回调机制(如
message_arrived
)。 - 遗嘱消息(Last Will):可在连接时设置遗嘱消息,用于客户端异常断线通知。
通过此实现,您已掌握 MQTT 的核心通信流程。实际项目中可根据需求扩展消息持久化、SSL加密等功能。
不同mqtt对比
关键差异说明
特性 | Paho MQTT C++ 库 | Mosquitto C 库 |
---|---|---|
编程风格 | 面向对象(C++封装) | 面向过程(C语言接口) |
安装复杂度 | 较高(需手动编译依赖) | 简单(直接 apt 安装) |
功能扩展性 | 更丰富的异步回调机制 | 基础功能 |
文档支持 | 官方文档详细 | 社区示例较多 |
推荐选择:
- 如果需高性能和异步特性,优先选择 Paho MQTT C++ 库。
- 如果快速验证或简单项目,直接使用 Mosquitto C 库。