给我一段ubuntu 下c++的mqtt代码 包含本机发送客户端 和 本机订阅客户端的代码
时间: 2024-04-17 17:25:09 浏览: 21
当然,下面是一个简单的示例代码,演示了如何在Ubuntu下使用C++进行MQTT通信。
发送客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <mqtt/async_client.h>
const std::string SERVER_ADDRESS { "tcp://localhost:1883" };
const std::string CLIENT_ID { "publisher" };
const std::string TOPIC { "test/topic" };
const int QOS = 1;
int main(int argc, char* argv[]) {
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try {
client.connect(connOpts)->wait();
std::cout << "Connected to the MQTT server" << std::endl;
std::string payload = "Hello, MQTT!";
mqtt::message_ptr pubmsg = mqtt::make_message(TOPIC, payload, QOS, false);
client.publish(pubmsg)->wait();
std::cout << "Message published: " << payload << std::endl;
client.disconnect()->wait();
std::cout << "Disconnected from the MQTT server" << std::endl;
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
return 0;
}
```
订阅客户端代码:
```cpp
#include <iostream>
#include <cstring>
#include <mqtt/async_client.h>
const std::string SERVER_ADDRESS { "tcp://localhost:1883" };
const std::string CLIENT_ID { "subscriber" };
const std::string TOPIC { "test/topic" };
const int QOS = 1;
class callback : public virtual mqtt::callback {
void message_arrived(mqtt::const_message_ptr msg) override {
std::cout << "Topic: " << msg->get_topic() << std::endl;
std::cout << "Message: " << msg->to_string() << std::endl;
}
};
int main(int argc, char* argv[]) {
mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);
callback cb;
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try {
client.connect(connOpts)->wait();
std::cout << "Connected to the MQTT server" << std::endl;
client.subscribe(TOPIC, QOS)->wait();
std::cout << "Subscribed to topic: " << TOPIC << std::endl;
client.start_consuming();
std::this_thread::sleep_for(std::chrono::seconds(10));
client.unsubscribe(TOPIC)->wait();
std::cout << "Unsubscribed from topic: " << TOPIC << std::endl;
client.stop_consuming();
client.disconnect()->wait();
std::cout << "Disconnected from the MQTT server" << std::endl;
} catch (const mqtt::exception& exc) {
std::cerr << "Error: " << exc.what() << std::endl;
return 1;
}
return 0;
}
```
以上代码使用了Paho C++库来实现MQTT通信。请确保已经安装了Paho C++库,并在编译代码时链接相应的库文件。希望这能帮助到你!