c-希望使用带有ssl的MQTT paho客户端与服务器test.mosquitto.org建立连接.我无法连接



这是我当前正在运行的代码,idk中我犯了错误,正在获取错误"quot"quot;连接失败,返回代码-1"quot"如果有任何帮助,我们将不胜感激,我正在树莓皮中运行此程序,提前感谢

#include <MQTTClient.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define ADDRESS "ssl://test.mosquitto.org:8884"
#define CLIENTID "c1"
#define TOPIC "ack"
#define PAYLOAD "Hello World"
#define QOS 1
#define TIMEOUT 10000L
void MQTTClient_global_init (   MQTTClient_init_options *   inits   );
int main() {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_DEFAULT,
NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.ssl = &ssl_opts;
conn_opts.ssl->trustStore = "client.crt";
conn_opts.ssl->keyStore = "client.key";
conn_opts.ssl->CApath = "mosquitto.org.crt";
conn_opts.serverURIcount = 0;
conn_opts.serverURIs = NULL;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
printf("Failed to connect, return code %dn", rc);
exit(EXIT_FAILURE);
}
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %sn"
"on topic %s for client with ClientID: %sn",
(int)(TIMEOUT / 1000), PAYLOAD, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d deliveredn", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return 0;
}

输出:连接失败,返回代码-1

根据Paho的源代码,获得-1错误的最简单方法是忘记初始化库。

您需要在程序开始时调用MQTTClient_global_init

最新更新