windows下paho.mqtt.c编译并使用SSL for MQTT
介绍
网上找了很多资料,要么不全要么说到一半,一直卡在ssl加密mqtt连接的配置,自己摸索花了很久的时间,因此写下这篇文章给各位码友避坑。本次工程使用vs2019,SSL需要openssl作为依赖,源码编译使用cmake GUI。
paho库下载
paho.mqtt.c仓库: https://github.com/eclipse/paho.mqtt.c
openssl安装
链接: https://slproweb.com/products/Win32OpenSSL.html
请根据自己的工程进行选择是X86的还是64位的。
cmake安装及编译
链接: https://cmake.org/download/
如果要编译64位的工程记得安装64位的工具,32位的工程选择32位的
1.再cmake选择下载的目录以及工程生产目录,我直接选择库目录,不影响~~~
2.配置选择:vs版本以及生成多少位的工程文件。 我选择的是32位
3.页面变成红色,直接无视点configure再次进行配置
4.选择ssl再次进行配置,cmake会自动选择选择openssl安装路径, 之后点击Generate生成工程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sEEfpIYi-1690809714192)(https://img-blog.csdnimg.cn/24b8ef5724b64a59aa9a28a5756386ae.png]
-
编译生成lib库文件:
选择release。编译工程
5.编译库文件,右键点击编译这四个工程,会生产4个lib文件和4个dll文件。
-
在新工程里使用paho库,将paho.mqtt.c里面的src文件移植到新工程目录
-
vs工程配置 : c/c++常规-附加包含目录、预处理器;链接器-附加依赖项 配置
(1)添加openssl路径以及src路径
(2)预处理定义,冲cmake生成的工程复制 过来即可
(3)附加库目录:lib文件目录
(4)添加lib依赖项, 从cmake复制即可
代码示例
#include "MQTTClient.h"
#include "MQTTClientPersistence.h"
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include "openssl/ssl.h"
#define PAYLOAD "{\"request\": \"test\"}"
int main(int argc, char** argv)
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
char sslServerAdd[40] = "ssl://171.26.33.22:1888";
char client_id[5] = "aaac";
char* addrs = sslServerAdd;
char* ids = client_id;
MQTTClient_create(&client, addrs, ids, MQTTCLIENT_PERSISTENCE_NONE, NULL);
ssl_opts.enableServerCertAuth = 0;
ssl_opts.sslVersion = MQTT_SSL_VERSION_DEFAULT;
conn_opts.ssl = &ssl_opts;
int rc = MQTTClient_connect(client, &conn_opts);
if (rc != MQTTCLIENT_SUCCESS) {
printf("fail !!\r\n");
}else{
printf("sucsucc !!\r\n");
}
MQTTClient_message* read_message;
MQTTClient_message send_message;
char* topicName;
char publish_topic[64];
char subscribe_topic[64];
sprintf(subscribe_topic, "app/command/response");
sprintf(publish_topic, "app/command/request");
MQTTClient_deliveryToken token = 0;
topicName = subscribe_topic;
rc = MQTTClient_subscribe(client, topicName, 0);
if (rc != MQTTCLIENT_SUCCESS )
{
printf("MQTT subscribe fail!");
}
topicName = publish_topic;
send_message.qos = 0;
send_message.retained = 0;
send_message.payload = PAYLOAD;
send_message.payloadlen = (int)strlen(PAYLOAD);
rc = MQTTClient_publish(client, topicName, send_message.payloadlen, send_message.payload, send_message.qos, send_message.retained, NULL);
if (rc != MQTTCLIENT_SUCCESS) {
printf("MQTT publish fail!");
return EXIT_SUCCESS;
}
read_message = NULL;
int topicLen;
char buf[1024];
topicName = subscribe_topic;
rc = MQTTClient_receive(client, &topicName, &topicLen, &read_message, 1000);
if (read_message)
{
memcpy(buf, (char*)read_message->payload, read_message->payloadlen);
printf("message : %s", buf);
}
return EXIT_SUCCESS;
}