在C语言中,使用MQTT协议进行动态主题订阅需要使用MQTT客户端库。其中,libmosquitto是一个广泛使用的开源MQTT客户端库。以下是一个使用libmosquitto库进行动态主题订阅的示例:
sudo apt-get install libmosquitto-dev
mqtt_subscribe.c
,并包含必要的头文件:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mosquitto.h>
int message_callback(void *userdata, struct mosquitto_message *message) {
printf("Received message: %s from topic: %s\n", message->payload, message->topic);
return 0;
}
main
函数中,初始化MQTT客户端,并连接到MQTT代理:int main(int argc, char *argv[]) {
int rc;
struct mosquitto *client;
const char *broker = "tcp://broker.hivemq.com:1883";
const char *client_id = "C_Client_1";
client = mosquitto_new(client_id, true, NULL);
if (!client) {
fprintf(stderr, "Failed to create mosquitto client\n");
return 1;
}
rc = mosquitto_connect(client, broker, 1883, 60);
if (rc != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "Failed to connect to broker: %d\n", rc);
mosquitto_destroy(client);
return 1;
}
test/topic/
开头的主题,并使用通配符+
来匹配任意长度的子主题:char *topic = "test/topic/+";
rc = mosquitto_subscribe(client, &topic, 0);
if (rc != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "Failed to subscribe to topic: %d\n", rc);
mosquitto_disconnect(client);
mosquitto_destroy(client);
return 1;
}
mosquitto_set_callback(client, message_callback);
mosquitto_loop_start(client);
mosquitto_disconnect(client);
mosquitto_destroy(client);
gcc mqtt_subscribe.c -o mqtt_subscribe -lmosquitto
./mqtt_subscribe
现在,程序将订阅test/topic/
开头的所有主题,并在接收到消息时打印出消息内容和主题。你可以根据需要修改主题和回调函数来满足你的需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。