简体   繁体   中英

How can I disable retries in mosquitto_connect() function?

Using this program:

/*
  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);
}

(It's the same one published in this post with a little difference: exit(1) removed in the connection callback for the fail case)

In case of wrong user/pass I'm getting a loop of error messages:

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.)
...

one per second, more or less.

Thus, I guess that mosquitto_connect() retries connection in case of fail so the connection callback is called on each attemp. This could make sense in the case of problems due to the network but in this case (wrong user/pass) it doesn't make sense to retry.

Thus, I'll prefer to manage connection errors and retries in my program logic. Is there any way to disable retries in mosquitto_connect() ? I have looked library documentation but I haven't found any parameter for that...

如果您停止客户端网络循环( mosquitto_loop_stop(mosq); ( mosquitto_loop_stop(mosq); ),它不会尝试重新连接,因为正是此循环处理重新连接周期。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM