【发布时间】:2021-06-08 02:44:15
【问题描述】:
我在 HiveMq 云中创建了一个 hiveMQ 集群,并创建了用户名和密码。
我从 Paho C 库创建了 MQTTClient_connectOptions 并将我的用户名和密码作为参数:
#define ADDRESS "myURL:8883" // broker address for use in local machine
#define CLIENTID "myclientID"
#define TOPIC "testtopic"
#define TIMEOUT 10000L // ms
#define USERNAME "myUsername"
#define PASSWORD "myPassword"
int main(int argc, char* argv[])
{
/* MQTT Client initialization */
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc; //status code received from broker
rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
printf("Client create reason code: %d\n", rc);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.username = USERNAME;
conn_opts.password = PASSWORD;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
// checks whether the connection is successful or not
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", (MQTTClient_connect(client, &conn_opts)));
exit(-1);
}
MQTTClient_message msg = MQTTClient_message_initializer;
/*
sending data
pass sensor data to this function for publishing
*/
rc = publish_message(client, TOPIC, msg, &token, "4561237891", "23.6", "170.3", "524.08");
// Disconnect
int timeout = 100; //second
MQTTClient_disconnect(client, timeout);
MQTTClient_destroy(&client);
return rc;
}
MQTTClient_connect 无法连接到代理并返回-1:
连接失败,返回码-1
我尝试使用 MQTT CLI 连接,它成功了,我发布并订阅了一个主题并传输了一条消息。所以我的认证是错误的。
如何正确连接 Paho C 库的简单身份验证?
【问题讨论】:
-
MQTTClient_create是否返回MQTTCLIENT_SUCCESS(0)? -
@Brits 是的,它会打印:
Client create reason code: 0 -
对不起 - 以为你得到了 -1 但...... 更改
printf("Failed to connect, return code %d\n"...以输出rc的值(当前你第二次调用MQTTClient_connect掩盖了真正的错误) . -
ADDRESS是否包含协议而不仅仅是主机:端口? -
@Brits:对,我改了,但还是打印出来:
Failed to connect, return code -1