提供一个简单的用c语言的Eclipse Paho MQTT的客户端代码
时间: 2024-03-21 14:42:08 浏览: 65
好的,以下是一个简单的 C 代码片段,用于连接到 MQTT 代理并发布消息,需要使用 Eclipse Paho MQTT C 客户端库:
```c
#include "MQTTClient.h"
#define ADDRESS "tcp://mqtt.eclipse.org:1883"
#define CLIENTID "c-sample"
#define TOPIC "test/topic"
#define PAYLOAD "Hello, World!"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[]) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_connect(client, &conn_opts);
pubmsg.payload = (void*)PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message delivered %d\n", rc);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
```
这个客户端连接到 Eclipse 的公共 MQTT 测试代理,并发布一条消息到 "test/topic" 主题。你可以根据你的实际需求进行修改。注意,需要在代码中引用 Paho MQTT C 客户端库头文件并链接该库。
阅读全文