c++基于mosqpp实现mqtt客户端 完整示例代码
时间: 2024-10-15 07:14:52 浏览: 59
在C++中使用MqttClient库(如Mosquitto C++客户端库mosquittopp)来实现MQTT客户端是一个常见的任务。以下是创建一个基本的MQTT客户端连接、订阅主题并接收消息的简单示例。请注意,这个例子假设您已经安装了mosquittopp库,并且已经在项目中包含了相应的头文件。
```cpp
#include <mosquitto.h>
#include <iostream>
class MqttClient {
public:
MqttClient(const std::string& broker_address, const std::string& client_id) :
mqtt_(mosquitto_new(client_id.c_str(), true, nullptr)) {}
void connect() {
if (mqtt_) {
mosquitto_connect(mqtt_, broker_address.c_str(), 1883, 60);
while (!mosquitto_connack_rdy(mqtt_)); // 等待连接完成
std::cout << "Connected to MQTT broker." << std::endl;
}
}
void subscribe(const std::string& topic) {
int result = mosquitto.subscribe(mqtt_, topic.c_str(), 1); // QoS 1 for at least once delivery
if (result == MOSQ_ERR_SUCCESS) {
std::cout << "Subscribed to topic: " << topic << std::endl;
} else {
std::cerr << "Failed to subscribe: " << mosquitto_error_string(result) << std::endl;
}
}
void on_message(const struct mosquitto_message* message) {
std::cout << "Received message on topic: " << message->topic << ", payload: " << std::string((char*)message->payload, message->payload_len) << std::endl;
}
private:
mosquitto* mqtt_;
};
int main() {
MqttClient client("localhost", "client-1");
client.connect();
client.subscribe("test/topic");
// 模拟消息接收,通常由 Mosquitto 库自动处理回调
mosquitto_loop_forever(mqtt_, -1);
// 关闭连接前,记得清理资源
mosquitto_destroy(mqtt_);
return 0;
}
阅读全文