#include <stdio.h> #include <stdlib.h> #include <string.h> #include "MQTTClient.h" #define MQTT_BROKER "mqtt.ddoss.cn" // MQTT代理服务器地址 #define MQTT_PORT 1883 // MQTT代理的默认端口,如果是TLS连接使用8883 #define MQTT_CLIENT_ID "CClient" // MQTT客户端ID,建议唯一 #define MQTT_TOPIC "test" // MQTT主题 #define MQTT_USERNAME "eisc" // MQTT用户名 #define MQTT_PASSWORD "000000" // MQTT密码 // 连接成功的回调函数 void on_connect(MQTTClient *c, int result_code) { if (result_code == 0) { printf("Connected to MQTT Broker successfully.\n"); // 连接成功后订阅主题 MQTTString topic = MQTTString_initializer; topic.cstring = MQTT_TOPIC; MQTTClient_subscribe(c, &topic, 1); } else { printf("Failed to connect, return code %d\n", result_code); } } // 消息到达的回调函数 void on_message(MQTTClient *c, char *topicName, int topicLen, MQTTClient_message *message) { printf("Received message on topic '%s': ", topicName); fwrite(message->payload, 1, message->payloadlen, stdout); printf("\n"); MQTTClient_freeMessage(&message); MQTTClient_free(topicName); } int main(int argc, char *argv[]) { MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; char *payload = "Hello MQTT from C!"; char *topic = "test"; MQTTClient_create(&client, MQTT_BROKER, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTClient_setCallbacks(client, NULL, on_connect, on_message); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.username = MQTT_USERNAME; conn_opts.password = MQTT_PASSWORD; if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS) { printf("Failed to connect to the MQTT server.\n"); exit(EXIT_FAILURE); } // 发布消息 pubmsg.payload = (void *)payload; pubmsg.payloadlen = strlen(payload); pubmsg.qos = 1; pubmsg.retained = 0; MQTTClient_publishMessage(client, topic, &pubmsg, &token); printf("Message published to topic '%s'\n", topic); // 等待消息发布完成 MQTTClient_waitCompletion(client, token, 1000); // 订阅主题接收消息 MQTTString topic = MQTTString_initializer; topic.cstring = topic; MQTTClient_subscribe(client, &topic, 1); // 循环处理消息 while (1) { MQTTClient_yield(client, 1000); } MQTTClient_disconnect(client, 1000); MQTTClient_destroy(&client); return 0; }
Powered by ddoss.cn 12.0
©2015 - 2024 ddoss
渝公网安备50011302222260号 渝ICP备2024035333号 【实验平台安全承诺书】 小绿叶技术社区,优化网络中,点击查看配置信息
您的IP:192.168.122.82,2024-10-10 18:12:44,Processed in 0.02938 second(s).