c++基于libmosquitto实现mqtt客户端 完整示例代码
时间: 2024-10-11 13:16:47 浏览: 40
mqtt开发C语言基于paho实现MQTT客户端实战案例
在C++中,利用libmosquitto库实现MQTT(Message Queuing Telemetry Transport)客户端是一个常见的任务。libmosquitto是一个轻量级、开源的C语言 MQTT客户端/服务器库。以下是一个简单的示例代码片段,展示如何创建一个基本的MQTT客户端连接并发送消息:
```cpp
#include " mosquitto.h "
// 创建 Mosquitto 实例
Mosquitto *client = new Mosquitto();
// 初始化 Mosquitto
int result = client->init();
if (result != MOSQ_ERR_SUCCESS) {
std::cerr << "Failed to initialize Mosquitto!" << std::endl;
delete client;
return -1;
}
// 连接到MQTT broker
std::string broker_address = "tcp://your_broker_ip:1883";
result = client->connect("my_client", broker_address.c_str(), 60);
if (result != MOSQ_ERR_SUCCESS) {
std::cerr << "Connection failed: " << mqtt_result_string(result) << std::endl;
delete client;
return -1;
}
// 订阅主题
std::string topic = "test/topic";
result = client->subscribe(topic.c_str());
if (result != MOSQ_ERR_SUCCESS) {
std::cerr << "Subscription failed: " << mqtt_result_string(result) << std::endl;
}
// 发送消息
std::string message = "Hello MQTT!";
result = client->publish(topic.c_str(), strlen(message), true, message);
if (result != MOSQ_ERR_SUCCESS) {
std::cerr << "Publishing failed: " << mqtt_result_string(result) << std::endl;
}
// 断开连接
result = client->disconnect();
if (result != MOSQ_ERR_SUCCESS) {
std::cerr << "Disconnect failed: " << mqtt_result_string(result) << std::endl;
}
// 清理资源
delete client;
阅读全文