#include <iostream>
#include <mqtt/async_client.h>
// MQTT服务器地址和端口
const std::string ADDRESS = "tcp://localhost:1883";
const std::string CLIENT_ID = "example_client";
// 回调类,用于处理MQTT事件
class callback : public virtual mqtt::callback {
public:
void connected(const std::string& cause) override {
std::cout << "\nConnected to broker\n" << std::endl;
}
void connection_lost(const std::string& cause) override {
std::cout << "\nConnection lost" << std::endl;
if (!cause.empty())
std::cout << " cause: " << cause << std::endl;
}
void message_arrived(mqtt::const_message_ptr msg) override {
std::cout << "Message arrived:" << std::endl;
std::cout << " Topic: '" << msg->get_topic() << "'" << std::endl;
std::cout << " Message: '" << msg->to_string() << "'" << std::endl;
}
void delivery_complete(mqtt::delivery_token_ptr token) override {
std::cout << "Delivery complete for token: " << token.get() << std::endl;
}
};
int main() {
// 创建异步客户端实例
mqtt::async_client client(ADDRESS, CLIENT_ID);
// 创建回调对象并将其设置给客户端
callback cb;
client.set_callback(cb);
// 连接到MQTT代理
mqtt::connect_options connOpts;
connOpts.set_clean_session(true);
try {
std::cout << "Connecting to the broker..." << std::endl;
client.connect(connOpts)->wait();
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
// 订阅主题
std::string topic = "test/topic";
int qos = 1;
try {
std::cout << "Subscribing to topic '" << topic << "' qos " << qos << std::endl;
client.subscribe(topic, qos)->wait();
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
// 发布消息
std::string payload = "Hello, World!";
try {
std::cout << "Publishing message on topic '" << topic << "' qos " << qos << std::endl;
client.publish(topic, payload, qos)->wait();
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
// 等待一段时间以接收消息
std::this_thread::sleep_for(std::chrono::seconds(5));
// 断开连接
try {
std::cout << "Disconnecting from broker..." << std::endl;
client.disconnect()->wait();
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
return 0;
}
引入库:
#include <iostream>
和 #include <mqtt/async_client.h>
分别用于标准输入输出和MQTT客户端库。常量定义:
ADDRESS
:MQTT服务器的地址和端口。CLIENT_ID
:客户端的唯一标识符。回调类:
callback
类继承自 mqtt::callback
,用于处理MQTT事件(如连接成功、连接丢失、消息到达等)。主函数:
mqtt::async_client
实例。这个示例展示了如何使用C++与MQTT协议进行通信,包括连接、订阅、发布和断开操作。
上一篇:c++ vector 初始化
下一篇:c++ exception
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站