mqtt客户端连接服务器的C语言代码实现
时间: 2023-08-12 18:08:53 浏览: 94
以下是一个简单的MQTT客户端连接服务器的C语言代码实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mosquitto.h>
void on_connect(struct mosquitto *mosq, void *userdata, int rc)
{
if(rc == 0) {
printf("Connected to MQTT broker successfully\n");
mosquitto_subscribe(mosq, NULL, "test", 0);
} else {
printf("Failed to connect to MQTT broker\n");
}
}
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg)
{
printf("Received message: %s\n", (char *)msg->payload);
}
int main()
{
struct mosquitto *mosq = NULL;
int rc;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true, NULL);
if(!mosq) {
printf("Failed to create MQTT client instance\n");
return 1;
}
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_message_callback_set(mosq, on_message);
rc = mosquitto_connect(mosq, "localhost", 1883, 60);
if(rc != MOSQ_ERR_SUCCESS) {
printf("Failed to connect to MQTT broker: %s\n", mosquitto_strerror(rc));
mosquitto_destroy(mosq);
return 1;
}
mosquitto_loop_forever(mosq, -1, 1);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
```
这个例子使用了Mosquitto库来实现MQTT客户端连接,包括连接回调函数(on_connect)和消息回调函数(on_message)。在主函数中,首先初始化Mosquitto库,然后创建MQTT客户端实例(mosq),然后设置连接回调函数和消息回调函数,然后连接到MQTT服务器并循环等待消息。当接收到来自MQTT服务器的消息时,消息回调函数(on_message)将被调用,打印消息的内容。最后,清除Mosquitto库并退出主函数。
阅读全文