c++ mqtt subscribe 代码示例
时间: 2023-12-21 18:29:35 浏览: 171
以下是一个C++ MQTT订阅的示例代码,使用Eclipse Paho C++库实现:
```c++
#include <iostream>
#include <cstring>
#include "mqtt/async_client.h"
const std::string SERVER_ADDRESS("tcp://localhost:1883");
const std::string CLIENT_ID("async_subcribe_cpp");
const std::string TOPIC("test/topic");
const int QOS = 1;
class callback : public virtual mqtt::callback
{
public:
virtual void connection_lost(const std::string& cause) override
{
std::cout << "\nConnection lost" << std::endl;
if (!cause.empty())
std::cout << "\tcause: " << cause << std::endl;
}
virtual void message_arrived(mqtt::const_message_ptr msg) override
{
std::cout << "Message arrived" << std::endl;
std::cout << "\ttopic: '" << msg->get_topic() << "'" << std::endl;
std::cout << "\tpayload: '" << msg->to_string() << "'\n" << std::endl;
}
virtual void delivery_complete(mqtt::delivery_token_ptr token) override {}
};
int main(int argc, char* argv[])
{
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
callback cb;
client.set_callback(cb);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try {
std::cout << "Connecting to the MQTT server..." << std::flush;
client.connect(connOpts)->wait();
std::cout << "OK" << std::endl;
std::cout << "Subscribing to topic '" << TOPIC << "'..." << std::flush;
client.subscribe(TOPIC, QOS)->wait();
std::cout << "OK" << std::endl;
while (true)
;
client.unsubscribe(TOPIC)->wait();
std::cout << "Unsubscribed" << std::endl;
client.disconnect()->wait();
std::cout << "Disconnected" << std::endl;
}
catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
return 0;
}
```
阅读全文