当前位置: 首页 > news >正文

基于C++在windows下使用mosquitto实现MQTT订阅客户端

1、MOSQUITTO订阅客户端搭建

  1 #include <iostream>
  2 #include <iostream>
  3 #include <thread>
  4 #include <mosquitto.h>
  5 
  6 //mqtt
  7 #define MQTT_USER_NAME "admin"
  8 #define MQTT_PASS_WORD "123456"
  9 #define MQTT_SERVER_IP_ADDRESS "10.57.6.250"
 10 #define MQTT_SERVER_PORT 1883
 11 #define PUBLISH_JSON_DATA_ORG "4321"
 12 static struct mosquitto* mosq;
 13 static bool mqtt_init_sign;
 14 //mqtt
 15 
 16 void on_message(struct mosquitto* mosq, void* userdata, const struct mosquitto_message* msg) {
 17     std::cout << "\nrev msg:" << std::endl;
 18     std::cout << "the topic of the msg is: " << msg->topic << std::endl;
 19 
 20     if (msg->payloadlen > 0) {
 21         std::string message(static_cast<char*>(msg->payload), msg->payloadlen);
 22         std::cout << "the msg content is: " << message.c_str() << std::endl;
 23     }
 24     else {
 25         std::cout << "the msg content is:null" << std::endl;
 26     }
 27 
 28     std::cout << "QoS: " << msg->qos << std::endl;
 29     std::cout << "the ID of the msg is: " << msg->mid << std::endl;
 30     std::cout << "---------------------" << std::endl;
 31 }
 32 
 33 void on_connect(struct mosquitto *mosq, void *obj, int rc) {
 34     if (rc == 0) {
 35         printf("authentication success\n");
 36     }
 37     else {
 38         printf("connect failed: %s\n", mosquitto_strerror(rc));
 39     }
 40 }
 41 
 42 void on_disconnect(struct mosquitto *mosq, void *obj, int rc) {
 43     printf("disconnect: %s\n", mosquitto_strerror(rc));
 44 
 45     if (rc == MOSQ_ERR_AUTH) {
 46         printf("error:authentication failure(username/password is wrong)\n");
 47     }
 48     else if (rc == MOSQ_ERR_CONN_REFUSED) {
 49         printf("error:access refused\n");
 50     }
 51 }
 52 
 53 int init_mqtt(const std::string username, const std::string passwd, const std::string hostname, const int port)
 54 {
 55     mosquitto_lib_init();
 56 
 57     mosq = mosquitto_new(nullptr, true, nullptr);//第一个形参制定为一个值后,派生类会出现发布数据失败的情况,因为不同的派生类共用一个client_id
 58     if (!mosq) {
 59         std::cerr << "Failed to create mosquitto instance!" << std::endl;
 60         return 0;
 61     }
 62 
 63     mosquitto_connect_callback_set(mosq, on_connect);
 64     mosquitto_disconnect_callback_set(mosq, on_disconnect);
 65     mosquitto_message_callback_set(mosq, on_message);
 66 
 67     const char* usrname = username.c_str();
 68     const char* password = passwd.c_str();
 69 
 70     int rc = mosquitto_username_pw_set(mosq, usrname, password);
 71     if (rc != MOSQ_ERR_SUCCESS) {
 72         std::cerr << "Failed to set username/password: " << mosquitto_strerror(rc) << std::endl;
 73         mosquitto_destroy(mosq);
 74         mosquitto_lib_cleanup();
 75         return 0;
 76     }
 77 
 78     rc = mosquitto_connect(mosq, hostname.c_str(), port, 60);
 79     if (rc != MOSQ_ERR_SUCCESS) {
 80         std::cerr << "Connection failed: " << mosquitto_strerror(rc) << std::endl;
 81 
 82         std::cout << "Trying without authentication..." << std::endl;
 83         mosquitto_username_pw_set(mosq, nullptr, nullptr);
 84 
 85         rc = mosquitto_connect(mosq, hostname.c_str(), port, 60);
 86         if (rc != MOSQ_ERR_SUCCESS) {
 87             std::cerr << "Still failed: " << mosquitto_strerror(rc) << std::endl;
 88             mosquitto_destroy(mosq);
 89             mosquitto_lib_cleanup();
 90             return 0;
 91         }
 92     }
 93 
 94     mosquitto_loop_start(mosq);
 95     mqtt_init_sign = true;
 96     return 1;
 97 }
 98 
 99 void subscribe_msg_from_server()
100 {
101     const char* topic = "TestMqttTopic";
102     int qos = 1;  // 服务质量等级 0,1,2
103 
104     int result = mosquitto_subscribe(mosq, NULL, topic, qos);
105     if (result != MOSQ_ERR_SUCCESS) {
106         std::cerr << "订阅失败: " << mosquitto_strerror(result) << std::endl;
107     }
108     else {
109         std::cout << "已订阅主题: " << topic << std::endl;
110     }
111 }
112 
113 int main()
114 {
115     init_mqtt(MQTT_USER_NAME, MQTT_PASS_WORD, MQTT_SERVER_IP_ADDRESS, MQTT_SERVER_PORT);
116 
117     while (1)
118     {
119         std::this_thread::sleep_for(std::chrono::milliseconds(5000));
120         std::cout << "start subscribe!" << std::endl;
121         subscribe_msg_from_server();
122     }
123 }

2、效果展示

MqttSub

 

http://www.jsqmd.com/news/274033/

相关文章:

  • Java就业越来越难,普通程序员如何突围上岸!
  • 2025中小企业低代码设备选型参考:斑斑(免费私有化)与飞书多维(生态协同)
  • 2026年重庆CAAC无人机培训机构推荐榜:无人机专业培训 /无人机培训/ 无人机培训机构/ 无人机培训学校/蓝天飞扬无人机培训机构精选
  • 福州研究生留学中介哪家强?口碑排名揭秘申请成功率高的优质机构 - 留学机构评审官
  • [吾爱大神原创工具] 一个开源、轻量、完全离线、跨平台的电脑工具箱
  • 网络安全自学:从入门到精通的路线图
  • [Windows] 3D圆球效果,年会抽奖神器
  • 智能驱动业务增长:2025年8大CRM系统选型全景指南 - 毛毛鱼的夏天
  • 2026年站桩养生功权威推荐榜:什么是站桩 /赵冀龙站桩/ 太极站桩/ 站桩好处/ 站桩养生/意拳站桩机构精选
  • 2026年解读:2025园区招商新趋势及实战指南,办公场地/园区/企业独栋,园区招商出租推荐排行 - 品牌推荐师
  • 2026年解读:2025园区招商新趋势及实战指南,办公场地/园区/企业独栋,园区招商出租推荐排行 - 品牌推荐师
  • 大厂裁员Java坑少人多,普通码农如何破局?
  • 别再只盯着开发和算法了!这5个方向(含网安)需求大涨,越老越吃香
  • 2026年口碑好的南京取名,宝宝取名,取名大师采购优选名录 - 品牌鉴赏师
  • Redis学到什么程度能在在Java面试中吊打大厂面试官!
  • 2026盘点海外名义雇主EOR公司,深度测评企业服务优势与合规出海路径 - 品牌2025
  • 2026年全球EOR服务商深度盘点与选择指南 - 品牌2025
  • SpringBoot完整知识体系梳理,这份笔记还是太全面了!
  • 2026出海德国合规雇佣全指南:Safeguard Global名义雇主EOR助力本地合规雇佣 - 品牌2025
  • vllm调参执行顺序最佳实践
  • 2026年北京沙盘模型制作公司实力推荐:地貌沙盘模型 /地产销售沙盘/ 智能交通沙盘 /城市智能沙盘/ 仿真模型沙盘 /工业沙盘模型服务机构精选
  • 拒绝内卷!冷门高薪职业来袭,人才缺口巨大,应届生月薪轻松过万
  • 2026 中专生考大数据与财务管理专业证书报考条件是什么?
  • 2026印度名义雇主EOR服务商推荐Safeguard Global助力布局全球市场 - 品牌2025
  • 2026HVV 蓝军完全指南:红蓝对抗战术与实战案例深度解析
  • hardfault问题怎么定位
  • 渭南少儿街舞教学机构推荐(2026 最新):3 家实力机构深度测评 - 华Sir1
  • 详细介绍:基于SpringBoot2+Vue2+uniapp的考研社区论坛网站及小程序
  • 渭南少儿爵士舞哪家靠谱?2026 三大优质品牌深度测评与选课攻略 - 华Sir1
  • 渭南成人爵士舞培训哪家强?三大培训机构实力盘点与推荐 - 华Sir1