使用C语言,编写MQTT客户端程序代码
时间: 2023-05-20 07:05:30 浏览: 144
以下是一个简单的MQTT客户端程序代码,使用C语言编写:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <mosquitto.h>
#define MQTT_HOST "localhost"
#define MQTT_PORT 1883
#define MQTT_TOPIC "test"
void on_connect(struct mosquitto *mosq, void *userdata, int result)
{
if(result == 0) {
printf("Connected to MQTT broker\n");
mosquitto_subscribe(mosq, NULL, MQTT_TOPIC, 0);
} else {
fprintf(stderr, "Failed to connect to MQTT broker: %s\n", mosquitto_strerror(result));
}
}
void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
printf("Received message on topic '%s': %s\n", message->topic, (char *)message->payload);
}
int main(int argc, char *argv[])
{
struct mosquitto *mosq = NULL;
int rc;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true, NULL);
if(!mosq) {
fprintf(stderr, "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, MQTT_HOST, MQTT_PORT, 60);
if(rc != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "Failed to connect to MQTT broker: %s\n", mosquitto_strerror(rc));
mosquitto_destroy(mosq);
return 1;
}
while(1) {
rc = mosquitto_loop(mosq, -1, 1);
if(rc != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "MQTT client loop error: %s\n", mosquitto_strerror(rc));
break;
}
}
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
阅读全文