you should be using the libmosquitto
link library provided by eclipse.
if this is the case, then mosquitto_connect
really does not have timeout
this parameter, its legal parameter is:
int mosquitto_connect(
struct mosquitto *mosq,
const char *host,
int port,
int keepalive);
Parameter is:
Parameters
mosq a valid mosquitto instance.
host the hostname or ip address of the broker to connect to.
port the network port to connect to. Usually 1883.
keepalive the number of seconds after which the broker should send a PING message to the client if no other messages have been exchanged in that time.
the return value is an int:
MOSQ_ERR_SUCCESS on success.
MOSQ_ERR_INVAL if the input parameters were invalid.
MOSQ_ERR_ERRNO if a system call returned an error. The variable errno contains the error code, even on Windows. Use strerror_r() where available or FormatMessage() on Windows.
notice the keepalive
here, which is the number of seconds that no return message has been received after sending the PING message. If the connection time exceeds this number, then mosquitto_connect
will not return MOSQ_ERR_SUCCESS
, so you can use keepalive
as the connection timeout. The details of the connection here can be seen in lib/connect.c . First acquire the read-write lock of socket, and then call mosquitto__reconnect
to set a lock with a time of keepalive
:
pthread_mutex_lock(&mosq->msgtime_mutex);
mosq->last_msg_in = mosquitto_time();
mosq->next_msg_out = mosq->last_msg_in + mosq->keepalive;
pthread_mutex_unlock(&mosq->msgtime_mutex);
keep reading in_packet
and out_packet
during keepalive. If the acquisition is successful, then the connection is successful. Otherwise, you can only wait for the keepalive
lock to expire naturally and return connection failure.
mosquitto_connect
is equivalent to a handshake for mosquitto connections. You can use mosquitto_reconnect
to reconnect after a failed connection. If reconnection is allowed n
times, then the total timeout
equals n * keepalive
. For example, here is an example where the number of reconnections is 3
:
int reconnect_time = 0;
int result = 1;
while (reconnect_time < 3 && result) {
result = mosquitto_connect(mosq, host, port, keepalive);
if(result){
fprintf(stderr, "Unable to connect, try to reconnect...\n");
reconnect_time += 1;
}
}
if (result) fprintf(stderr, "Connect failed").
and mosquitto_loop_forever
has a int timeout
parameter, which is the timeout for keeping the connection after the connection is established.
reference:
mosqutto.h: mosquitto_connect
/ eclipse/mosquitto/lib/connect.c