您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。