使用这个程序:
/*
compile using:
$ gcc -o libmosq libmosq.c -lmosquitto
*/
#include <stdio.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <unistd.h>
void connection_callback(struct mosquitto* mosq, void *obj, int rc)
{
if (rc) {
printf("connection error: %d (%s)\n", rc, mosquitto_connack_string(rc));
}
else {
printf("connection success\n");
}
}
int main(int argc, char *argv[])
{
struct mosquitto *mosq = NULL;
mosquitto_lib_init();
mosq = mosquitto_new(NULL, true, NULL);
if(!mosq) {
fprintf(stderr, "Error: Out of memory.\n");
exit(1);
}
mosquitto_connect_callback_set(mosq, connection_callback);
mosquitto_username_pw_set(mosq, "user1", "passwd1");
int resultCode = mosquitto_connect(mosq, "localhost", 1883, 60);
if (resultCode != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "error calling mosquitto_connect\n");
exit(1);
}
int loop = mosquitto_loop_start(mosq);
if(loop != MOSQ_ERR_SUCCESS){
fprintf(stderr, "Unable to start loop: %i\n", loop);
exit(1);
}
// hang until control+C is done
sleep(1000000);
}
(与这篇文章中发布的相同,略有不同:exit(1)
在失败情况的连接回调中删除)
如果用户/密码错误,我会收到一个错误消息循环:
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
connection error: 5 (Connection Refused: not authorised.)
...
每秒一个,或多或少。
因此,我猜想mosquitto_connect()
在失败的情况下重试连接,因此每次尝试都会调用连接回调。这在网络出现问题的情况下可能有意义,但在这种情况下(错误的用户/密码)重试没有意义。
因此,我更愿意在我的程序逻辑中管理连接错误和重试。有什么办法可以禁用重试mosquitto_connect()
吗?我查看了库文档,但没有找到任何参数...