文章目錄
- 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 庫。