MQTT C++ windows端 订阅端

此代码示例展示了如何使用MQTT异步库在Windows环境下建立连接、订阅主题、处理消息及断开连接的过程。程序包括连接丢失后的自动重连、订阅成功回调以及接收到消息的处理函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <fstream>
#include <iostream>
#include "md5.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdio.h> 
#include <malloc.h>
using namespace std;
#pragma comment(lib, "paho-mqttpp3.lib")  //加载的.lib文件





#include <windows.h>
extern "C" {
#include <MQTTAsync.h>    // 包含异步头
#include <MQTTClientPersistence.h>
#include <MQTTClient.h>    // 包含异步头

}

#define ADDRESS  "tcp://localhost:7788"
#define CLIENTID "Clent"
#define TOPIC    "MQTT"
#define PAYLOAD  "Hello World!"
#define QOS      1
#define TIMEOUT  10000L
volatile MQTTAsync_token deliveredtoken;


int disc_finished = 0;
int subsribed = 0;
int finished = 0;

const char* mqttUserName = "admin";
const char* mqttPassword = "123456";



void connlost(void* context, char* cause)
{
    MQTTAsync client = (MQTTAsync)context;
    MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
    int rc;
    printf("\nConnect lost\n");
    if (cause)
        printf("cause: %s\n", cause);
    printf("Reconneting\n");
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
    {
        printf("Failed to start connect, return code %d\n", rc);
        finished = 1;
    }
}

int msgarrvd(void* context, char* topicName, int topiclen, MQTTAsync_message* message)
{
    int i;
    char* payloadptr;
    printf("Message arrived\n");
    printf("topic: %s\n", topicName);
    printf("message:");
    payloadptr = (char*)message->payload;
    for (i = 0; i < message->payloadlen; i++)
    {
        putchar(*payloadptr++);
    }
    putchar('\n');
    MQTTAsync_freeMessage(&message);
    MQTTAsync_free(topicName);
    return 1;
}

void onDisconnet(void* context, MQTTAsync_successData* response)
{
    printf("Successful disconnection\n");
    disc_finished = 1;
}

void onSubscribe(void* context, MQTTAsync_successData* response)
{
    printf("Subsrive successed\n");
    subsribed = 1;
}

void onSubsribeFailure(void* context, MQTTAsync_failureData* response)
{
    printf("Subscribe failed, rc %d\n", response ? response->code : 0);
    finished = 1;
}

void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
    printf("Connect failed, rc %d\n", response ? response->code : 0);
    finished = 1;
}


void onConnect(void* context, MQTTAsync_successData* response)
{
    MQTTAsync client = (MQTTAsync)context;
    MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
    int rc;
    printf("Successful connection\n");
    printf("Subscruibing to topic %s\n for client %s\n using Qos %d\n\n" "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    opts.onSuccess = onSubscribe;
    opts.onFailure = onSubsribeFailure;
    opts.context = client;
    deliveredtoken = 0;
    if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
    {
        printf("Failed to start subsribe, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char* argv[])
{
    int rc;
    int ch;
    MQTTAsync client;

    MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
    MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;

    MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL);

    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.onSuccess = onConnect;
    conn_opts.onFailure = onConnectFailure;
    conn_opts.context = client;
    conn_opts.username = mqttUserName;
    conn_opts.password = mqttPassword;
    if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
    {
        printf("Failed to start connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    while (!subsribed)
        Sleep(3);
    if (finished)
        goto exit;
    do
    {
        ch = getchar();
    } while (ch != 'Q' && ch != 'q');

    disc_opts.onSuccess = onDisconnet;
    if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
    {
        printf("Failed to start disconnect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    while (!disc_finished)
        Sleep(3);

exit:
    MQTTAsync_destroy(&client);
    return rc;

}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值