您好,登錄后才能下訂單哦!
MQTT(Message Queuing Telemetry Transport)是一種輕量級(jí)的發(fā)布/訂閱消息傳輸協(xié)議,廣泛應(yīng)用于物聯(lián)網(wǎng)場(chǎng)景。下面是一個(gè)簡(jiǎn)單的C語(yǔ)言實(shí)現(xiàn)MQTT客戶端,該客戶端可以訂閱多個(gè)主題。
首先,你需要安裝一個(gè)MQTT庫(kù),例如libmosquitto。在Ubuntu系統(tǒng)中,可以使用以下命令安裝:
sudo apt-get install libmosquitto-dev
接下來(lái),創(chuàng)建一個(gè)C文件,例如mqtt_subscribe.c
,并編寫以下代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mosquitto.h>
#define TOPIC1 "/topic1"
#define TOPIC2 "/topic2"
#define BUFFER_SIZE 256
void on_connect(struct mosquitto *mosq, void *userdata, int rc) {
printf("Connected with result code %d\n", rc);
mosquitto_subscribe(mosq, TOPIC1, 0);
mosquitto_subscribe(mosq, TOPIC2, 0);
}
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) {
printf("Received message on topic: %s\n", msg->topic);
printf("Message: %s\n", msg->payload);
}
void on_publish(struct mosquitto *mosq, void *userdata, int mid) {
printf("Message %d published.\n", mid);
}
void on_subscribe(struct mosquitto *mosq, void *userdata, int mid, int granted_qos) {
printf("Subscribed: %d\n", mid);
}
void on_disconnect(struct mosquitto *mosq, void *userdata, int rc) {
printf("Disconnected.\n");
}
int main(int argc, char *argv[]) {
struct mosquitto *mosq;
int rc;
if (argc != 2) {
printf("Usage: %s <broker address>\n", argv[0]);
return 1;
}
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true);
if (!mosq) {
printf("Failed to create mosquitto client\n");
return 1;
}
mosquitto_username_pw_set(mosq, "your_username", "your_password");
mosquitto_connect(mosq, argv[1], 1883, 60);
mosquitto_set_callback(mosq, on_connect, on_message, on_publish, on_subscribe, on_disconnect);
rc = mosquitto_loop_start(mosq);
if (rc != MOSQ_ERR_SUCCESS) {
printf("Failed to start loop\n");
return 1;
}
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
在這個(gè)示例中,我們定義了兩個(gè)主題TOPIC1
和TOPIC2
,并在連接成功后訂閱這兩個(gè)主題。當(dāng)收到消息時(shí),會(huì)打印出消息的主題和內(nèi)容。
要編譯這個(gè)程序,使用以下命令:
gcc mqtt_subscribe.c -o mqtt_subscribe -lmosquitto
然后,運(yùn)行編譯后的程序,并提供MQTT代理的地址:
./mqtt_subscribe your_mqtt_broker_address
這樣,你就可以訂閱多個(gè)主題并接收消息了。注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要處理更多的錯(cuò)誤情況和邊緣情況。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。