MQTT 订阅接收消息 mosquitto 方式

1 说明

   采用 mosquitto 库,实现订阅主题,并接收消息。
   其中服务器有做限制,需要对应的 cilent id ,cafile 、certfile  、keyfile 等配置

2 环境

采用ubuntu 直接编译调试
安装mosquitto 库

sudo apt install libmosquitto-dev
sudo apt-get install mosquitto

3 代码实现

#include 
#include 
#include 
#include 

#define MQTT_HOST "akhrsh85xmt1q-ats.iot.us-east-1.amazonaws.com"
#define MQTT_PORT 8883
#define MQTT_TOPIC "test_topic/recv"
#define MQTT_CERT_PATH "/home/sky/develop/test/mosqito/cert.pem"
#define MQTT_KEY_PATH "/home/sky/develop/test/mosqito/key.pem"
#define MQTT_CA_PATH "/home/sky/develop/test/mosqito/ca.pem"
#define MQTT_CLIENT_ID "ID_666"


void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) {
    printf("Received message: %s\n", (char *)message->payload);
}

int main() {
    struct mosquitto *mosq = NULL;
    int rc;

    // 初始化 mosquitto 库
    mosquitto_lib_init();

    // 创建 mosquitto 客户端实例
    mosq = mosquitto_new(MQTT_CLIENT_ID, true, NULL);
    if (!mosq) {
        printf("Failed to create mosquitto instance.\n");
        return 1;
    }

    // 设置 TLS 证书
    rc = mosquitto_tls_set(mosq, MQTT_CA_PATH, NULL, MQTT_CERT_PATH, MQTT_KEY_PATH, NULL);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("Failed to set TLS certificate.\n");
        return 1;
    }

    // 连接 MQTT 服务器
    rc = mosquitto_connect(mosq, MQTT_HOST, 8883, 60);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("Failed to connect to MQTT server.\n");
        return 1;
    }

    // 订阅主题
    rc = mosquitto_subscribe(mosq, NULL, MQTT_TOPIC, 0);
    if (rc != MOSQ_ERR_SUCCESS) {
        printf("Failed to subscribe to topic.\n");
        return 1;
    }

    // 设置消息回调函数
    mosquitto_message_callback_set(mosq, on_message);

    // 循环处理消息
    while (1) {
        rc = mosquitto_loop(mosq, -1, 1);
        if (rc != MOSQ_ERR_SUCCESS) {
            printf("Failed to process messages.\n");
            break;
        }
    }

    // 断开连接并清理资源
    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    return 0;
}

对应的makefile

all: mqtt_sub

mqtt_sub: mqtt_sub.o
	gcc -o mqtt_sub mqtt_sub.o -lmosquitto

mqtt_sub.o: mqtt_sub.c
	gcc -c mqtt_sub.c

clean:
	rm -f mqtt_sub mqtt_sub.o

4 调试

4.1 编译

sky@ubuntu:~/develop/test/mosqito$ make
gcc -c mqtt_sub.c
gcc -o mqtt_sub mqtt_sub.o -lmosquitto

4.2 对应发送端的发送

此工具为 亚马逊的测试平台,可根据自己的实际情况,采用其他的测试工具或者linux下的发送命令
MQTT 订阅接收消息 mosquitto 方式_第1张图片

4.3 接收端

sky@ubuntu:~/develop/test/mosqito$ 
sky@ubuntu:~/develop/test/mosqito$ ./mqtt_sub
Received message: {
  "message": "1111"
}

你可能感兴趣的:(Linux,mqtt,linux,mqtt,mosquitto,C)