Paho MQTT C库多话题订阅代码
时间: 2023-09-21 17:08:51 浏览: 71
文章《C语言基于paho实现MQTT客户端实战案例》项目代码和依赖库文件
好的,以下是使用 Paho MQTT C 库实现多话题订阅的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <MQTTClient.h>
#define ADDRESS "tcp://mqtt.example.com:1883"
#define CLIENTID "ExampleClientSub"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message* msg = NULL;
MQTTClient_deliveryToken token;
int rc;
// 创建 MQTT 客户端实例
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
// 设置连接选项
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
// 连接到 MQTT 代理服务器
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Connected to MQTT broker\n");
// 订阅多个主题
const char* topics[] = {"test/topic1", "test/topic2", "test/topic3"};
int qos[] = {QOS, QOS, QOS};
int count = sizeof(topics) / sizeof(char*);
MQTTClient_subscribeMany(client, count, topics, qos);
// 循环接收消息
while (1) {
MQTTClient_messageArrived(client, NULL, msg);
printf("Received message on topic: %s, payload: %.*s\n", msg->topicName->lenstring.data, (int)msg->payloadlen, (char*)msg->payload);
MQTTClient_freeMessage(&msg);
MQTTClient_free(topicName);
}
// 断开连接
MQTTClient_disconnect(client, TIMEOUT);
MQTTClient_destroy(&client);
return rc;
}
```
在以上代码中,首先创建了一个 MQTT 客户端实例,并设置连接选项。然后连接到 MQTT 代理服务器,如果连接失败则打印错误信息并退出程序。
接着使用 `MQTTClient_subscribeMany()` 方法订阅多个主题,其中 `topics` 数组存储了多个主题名称,`qos` 数组存储了对应主题的 QoS 等级。
最后使用循环不断接收消息,并打印输出消息的主题和负载内容,直到程序被手动终止为止。
希望这个示例能够帮助到你。
阅读全文