c++基于mosqpp实现mqtt客户端 给服务端推送数据 完整示例代码
时间: 2024-10-15 14:16:36 浏览: 46
C#使用MQTT测试,客户端和服务端
4星 · 用户满意度95%
在C++中,你可以使用Mqtt_cpp库(mosquittopp)来实现MQTT客户端并向服务端推送数据。以下是一个简单的示例代码:
```cpp
#include <mosquittopp.h>
class MyClient : public mosquitto::mosquittopp {
public:
MyClient(const std::string& broker) : mosquitto::mosquittopp(), broker(broker) {
setup();
}
private:
void on_connect(int rc) override {
if (rc == 0) {
std::cout << "Connected to MQTT Broker (" << broker << ") with result code " << rc << std::endl;
subscribe("my/topic");
} else {
std::cerr << "Failed to connect, return code " << rc << std::endl;
}
}
void on_message(const mosquitto::message& msg) override {
std::cout << "Received message '" << msg.topic() << "' => " << msg.payload().c_str() << std::endl;
}
void publish_data() {
const std::string data = "Hello from MQTT Client";
publish("my/topic", data);
std::cout << "Published: " << data << std::endl;
}
private:
std::string broker;
};
int main() {
try {
MyClient client("tcp://your-broker-url:1883");
client.loop_start();
// 每隔5秒推送一次数据
std::this_thread::sleep_for(std::chrono::seconds(5));
while (!client.is_connected()) {
client.reconnect();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
// 发布消息到主题"my/topic"
client.publish_data();
// 阻塞等待断开连接或用户请求退出
while (client.loop()) {}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,我们创建了一个`MyClient`类,它继承自`mosquitto::mosquittopp`,并实现了`on_connect`和`on_message`回调函数。`publish_data`方法用于发送数据到MQTT服务器。
注意:
1. 将`"tcp://your-broker-url:1883"`替换为你实际的MQTT broker地址和端口。
2. 运行此程序之前,需要安装Mqtt_cpp库,并链接到项目中。
阅读全文