MQTT C++ windows端 订阅端

#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;

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Mosquitto本身是一个MQTT代理,而不是一个MQTT服务器。如果你需要一个MQTT服务器,可以考虑使用Eclipse Mosquitto的扩展版本Mosquitto.rsmb,它提供了一个MQTT服务器实现,可以用来实现自己的MQTT服务器。 以下是一个基于Mosquitto.rsmb的MQTT C++服务器示例代码: ```cpp #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <unistd.h> #include <cstring> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <mosquitto.h> #include <pthread.h> #define MQTT_PORT 1883 #define MQTT_KEEP_ALIVE 60 #define MAX_CLIENTS 1024 static void on_connect(struct mosquitto *mosq, void *userdata, int rc) { if (rc == 0) { std::cout << "Connected to MQTT broker" << std::endl; } else { std::cerr << "Failed to connect to MQTT broker: " << mosquitto_connack_string(rc) << std::endl; } } static void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) { std::cout << "Received message on topic " << msg->topic << ": " << (char *)msg->payload << std::endl; } class Client { public: Client(int fd) : fd_(fd), mosq_(NULL) {} ~Client() { if (mosq_) { mosquitto_destroy(mosq_); mosq_ = NULL; } if (fd_ > 0) { close(fd_); fd_ = -1; } } int fd() const { return fd_; } void start() { mosq_ = mosquitto_new(NULL, true, this); if (!mosq_) { std::cerr << "Failed to create Mosquitto object" << std::endl; return; } mosquitto_connect_callback_set(mosq_, on_connect); mosquitto_message_callback_set(mosq_, on_message); int rc = mosquitto_socket(mosq_); if (rc == MOSQ_ERR_SUCCESS) { rc = mosquitto_loop_start(mosq_); } if (rc != MOSQ_ERR_SUCCESS) { std::cerr << "Failed to start Mosquitto loop: " << mosquitto_strerror(rc) << std::endl; return; } char buf[1024]; while (true) { int n = recv(fd_, buf, sizeof(buf), 0); if (n <= 0) { break; } mosquitto_raw_publish(mosq_, NULL, "test_topic", n, buf, 0, false); } } private: int fd_; struct mosquitto *mosq_; }; void *client_handler(void *arg) { Client *client = (Client *)arg; client->start(); delete client; return NULL; } int main(int argc, char **argv) { int listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (listen_fd < 0) { perror("Failed to create socket"); return 1; } struct sockaddr_in addr; std::memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(MQTT_PORT); int optval = 1; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Failed to bind socket"); return 1; } if (listen(listen_fd, SOMAXCONN) < 0) { perror("Failed to listen on socket"); return 1; } std::cout << "Listening on port " << MQTT_PORT << std::endl; while (true) { int conn_fd = accept(listen_fd, NULL, NULL); if (conn_fd < 0) { perror("Failed to accept connection"); continue; } std::cout << "Accepted connection from " << inet_ntoa(addr.sin_addr) << std::endl; pthread_t tid; pthread_create(&tid, NULL, client_handler, new Client(conn_fd)); pthread_detach(tid); } close(listen_fd); return 0; } ``` 此代码使用Mosquitto.rsmb作为MQTT服务器,并在本地的1883口监听连接。在接受到客户连接之后,它会启动一个新线程来处理该客户连接。在处理过程中,它会接收客户的消息,并使用Mosquitto API将其发布到名为“test_topic”的主题上。 请注意,此代码仅供参考,并不是一个完整的MQTT服务器实现。在实际使用中,还需要考虑安全性、可靠性、性能等因素。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值