您好,登錄后才能下訂單哦!
MQTT(Message Queuing Telemetry Transport)是一種輕量級的發布/訂閱消息傳輸協議,廣泛應用于物聯網場景。下面是一個簡單的C語言實現MQTT客戶端,該客戶端可以訂閱多個主題。
首先,你需要安裝一個MQTT庫,例如libmosquitto。在Ubuntu系統中,可以使用以下命令安裝:
sudo apt-get install libmosquitto-dev
接下來,創建一個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;
}
在這個示例中,我們定義了兩個主題TOPIC1
和TOPIC2
,并在連接成功后訂閱這兩個主題。當收到消息時,會打印出消息的主題和內容。
要編譯這個程序,使用以下命令:
gcc mqtt_subscribe.c -o mqtt_subscribe -lmosquitto
然后,運行編譯后的程序,并提供MQTT代理的地址:
./mqtt_subscribe your_mqtt_broker_address
這樣,你就可以訂閱多個主題并接收消息了。注意,這個示例僅用于演示目的,實際應用中可能需要處理更多的錯誤情況和邊緣情況。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。