linux c paho mqtt 接受很多条消息
时间: 2023-08-07 10:35:30 浏览: 142
MQTT每次断连重连后重复接收到消息-附件资源
在 Linux C 环境下,使用 Paho MQTT 接收多条消息可以通过循环接收的方式实现。以下是一个使用 Paho MQTT C 客户端接收多条消息的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "test"
#define QOS 1
#define TIMEOUT 10000L
volatile MQTTClient_deliveryToken deliveredtoken;
void messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
printf("Message arrived on topic %s: %.*s\n", topicName, message->payloadlen, (char*)message->payload);
deliveredtoken = message->msgid;
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
}
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
int rc;
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTClient_setCallbacks(client, NULL, NULL, messageArrived, NULL);
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
if ((rc = MQTTClient_subscribe(client, TOPIC, QOS)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to subscribe, return code %d\n", rc);
exit(EXIT_FAILURE);
}
int count = 10;
while (count--)
{
MQTTClient_deliveryToken token;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
char* message = "Hello, MQTT!";
pubmsg.payload = message;
pubmsg.payloadlen = strlen(message);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Message with delivery token %d sent\n", token);
MQTTClient_yield();
}
while (1)
{
MQTTClient_yield();
}
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
```
在上面的示例代码中,我们首先连接到 MQTT 服务器并订阅指定的主题。然后,我们使用一个循环来多次发送相同的消息。在循环中,我们创建了一个 MQTT 消息(MQTTClient_message)对象,并使用 MQTT 客户端对象的 MQTTClient_publishMessage 方法来发送该消息。接着,我们使用 MQTT 客户端对象的 MQTTClient_yield 方法来等待消息到达。在消息到达时,我们定义了一个回调函数(messageArrived)来处理接收到的消息,然后释放相关资源并继续等待下一条消息的到达。最后,我们使用一个死循环来保持程序的运行,并在需要时断开与服务器的连接并释放资源。
需要注意的是,在使用 Paho MQTT C 客户端接收多条消息时,需要定义一个回调函数来处理接收到的消息,并根据需要进行错误处理和重试等操作。同时,由于 C 语言不支持自动垃圾回收,因此需要手动释放资源,避免出现内存泄露等问题。
阅读全文