MQTT 客户端 C 源码
时间: 2023-12-08 11:52:11 浏览: 72
以下是一个简单的 MQTT 客户端 C 语言代码示例,使用了 Eclipse 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 "MQTT Examples"
#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;
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
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);
}
printf("Subscribed to topic %s\n", TOPIC);
printf("Waiting for messages...\n");
while (1)
{
MQTTClient_receive(client, &msg, TIMEOUT);
if (msg)
{
printf("Received message: %.*s\n", msg->payloadlen, (char*)msg->payload);
MQTTClient_freeMessage(&msg);
MQTTClient_free(msg);
}
}
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
```
这个 MQTT 客户端代码简单地连接到本地主机的 MQTT 代理,订阅了名为“MQTT Examples”的主题,并等待来自该主题的消息。在收到消息时,它会简单地输出消息内容。
阅读全文