j基于mosquitto的mqtt的c++代码
时间: 2024-03-26 08:38:33 浏览: 126
MyMosquitpp.zip
以下是一个基于Mosquitto的MQTT C++客户端示例代码:
```cpp
#include <iostream>
#include <cstring>
#include <mosquitto.h>
#define MQTT_HOST "localhost"
#define MQTT_PORT 1883
#define MQTT_KEEP_ALIVE 60
void on_connect(struct mosquitto *mosq, void *userdata, int rc) {
if (rc == 0) {
std::cout << "Connected to MQTT broker" << std::endl;
} else {
std::cerr << "Failed to connect to MQTT broker: " << mosquitto_connack_string(rc) << std::endl;
}
}
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) {
std::cout << "Received message on topic " << msg->topic << ": " << (char *)msg->payload << std::endl;
}
int main(int argc, char **argv) {
mosquitto_lib_init();
struct mosquitto *mosq = mosquitto_new(NULL, true, NULL);
if (!mosq) {
std::cerr << "Failed to create Mosquitto object" << std::endl;
return 1;
}
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_message_callback_set(mosq, on_message);
int rc = mosquitto_connect(mosq, MQTT_HOST, MQTT_PORT, MQTT_KEEP_ALIVE);
if (rc != MOSQ_ERR_SUCCESS) {
std::cerr << "Failed to connect to MQTT broker: " << mosquitto_strerror(rc) << std::endl;
return 1;
}
rc = mosquitto_subscribe(mosq, NULL, "test_topic", 0);
if (rc != MOSQ_ERR_SUCCESS) {
std::cerr << "Failed to subscribe to topic: " << mosquitto_strerror(rc) << std::endl;
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 1;
}
rc = mosquitto_loop_forever(mosq, -1, 1);
if (rc != MOSQ_ERR_SUCCESS) {
std::cerr << "Failed to start Mosquitto loop: " << mosquitto_strerror(rc) << std::endl;
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 1;
}
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
```
此代码使用Mosquitto C库连接到MQTT代理并订阅“test_topic”主题。在收到消息时,它将调用on_message回调函数并打印消息内容。可以使用mosquitto_publish函数在代理上发布消息。
阅读全文