您好,登錄后才能下訂單哦!
在C語言中,使用MQTT協(xié)議進(jìn)行動(dòng)態(tài)主題訂閱需要使用MQTT客戶端庫。其中,libmosquitto是一個(gè)廣泛使用的開源MQTT客戶端庫。以下是一個(gè)使用libmosquitto庫進(jìn)行動(dòng)態(tài)主題訂閱的示例:
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
函數(shù)中,初始化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
現(xiàn)在,程序?qū)⒂嗛?code>test/topic/開頭的所有主題,并在接收到消息時(shí)打印出消息內(nèi)容和主題。你可以根據(jù)需要修改主題和回調(diào)函數(shù)來滿足你的需求。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。