赞
踩
安装依赖项:
sudo apt-get update sudo apt-get install libpaho-mqttpp-dev libpaho-mqtt-dev
下载和编译Eclipse Paho MQTT C++库:
- git clone https://github.com/eclipse/paho.mqtt.cpp.git
- cd paho.mqtt.cpp
- mkdir build
- cd build
- cmake ..
- make
- sudo make install
- #include <iostream>
- #include <string>
- #include <chrono>
- #include <thread>
- #include "mqtt/async_client.h"
-
- // 定义MQTT服务器地址和客户端ID
- const std::string SERVER_ADDRESS("tcp://mqtt.eclipse.org:1883");
- const std::string CLIENT_ID("paho_cpp_async_publish_subscribe");
-
- const std::string TOPIC("test_topic");
- const int QOS = 1;
- const auto TIMEOUT = std::chrono::seconds(10);
-
- class callback : public virtual mqtt::callback,
- public virtual mqtt::iaction_listener
- {
- // 消息到达时的回调函数
- 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 << " payload: '" << msg->to_string() << "'" << 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 on_failure(const mqtt::token& tok) override {
- std::cout << "Subscription failed" << std::endl;
- }
-
- void on_success(const mqtt::token& tok) override {
- std::cout << "Subscription succeeded" << std::endl;
- }
- };
-
- int main(int argc, char* argv[]) {
- // 创建MQTT异步客户端
- mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
-
- // 设置回调函数
- callback cb;
- client.set_callback(cb);
-
- // 设置连接选项
- mqtt::connect_options connOpts;
- connOpts.set_clean_session(true);
-
- try {
- // 连接到MQTT服务器
- std::cout << "Connecting to the MQTT server..." << std::flush;
- mqtt::token_ptr conntok = client.connect(connOpts);
- conntok->wait();
- std::cout << "OK" << std::endl;
-
- // 订阅主题
- std::cout << "Subscribing to topic '" << TOPIC << "'..." << std::flush;
- client.subscribe(TOPIC, QOS, nullptr, cb);
- std::cout << "OK" << std::endl;
-
- // 发布消息
- std::string payload = "Hello, MQTT!";
- mqtt::message_ptr pubmsg = mqtt::make_message(TOPIC, payload);
- pubmsg->set_qos(QOS);
- client.publish(pubmsg)->wait_for(TIMEOUT);
- std::cout << "Message published" << std::endl;
-
- // 等待一段时间,以接收消息
- std::this_thread::sleep_for(std::chrono::seconds(10));
-
- // 断开连接
- std::cout << "Disconnecting from the MQTT server..." << std::flush;
- conntok = client.disconnect();
- conntok->wait();
- std::cout << "OK" << std::endl;
- }
- catch (const mqtt::exception& exc) {
- std::cerr << exc.what() << std::endl;
- return 1;
- }
-
- return 0;
- }
创建CMakeLists.txt:
- cmake_minimum_required(VERSION 3.5)
- project(MQTTClient)
-
- set(CMAKE_CXX_STANDARD 11)
-
- find_package(PahoMqttCpp REQUIRED)
-
- add_executable(MQTTClient main.cpp)
- target_link_libraries(MQTTClient PahoMqttCpp::paho-mqttpp3)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。