您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。