publishmqttmosquittolibmosquitto

mosquitto_publish returns MOSQ_ERR_SUCCESS eventhough MQTT broker is not running


I connected to MQTT broker using Mosquitto C client libraray.

I used below code for connection.

ret = mosquitto_connect (mosq, MQTT_HOSTNAME, MQTT_PORT, 0);

After connecting to broker I stopped the broker service.

Now I tried to publish message using below code.

ret = mosquitto_publish (mosq, NULL,topic, strlen (text), text, 1, 1);

Eventhough the broker is running, mosquitto_publish API returns success. When calling mosquitto_publish API second time, it returns 14.

Why mosquitto_publish returns success evethough the broker is running?How to fix this issue?

Thanks in advance.


Solution

  • When used together with mosquitto_start(), the mosquitto_publish() function is entirely asynchronous. All it does is add a new message to the queue and wake up the network thread. If everything was fine the last time the client attempted to communicate with the broker, then we have no way of knowing that the connection is down. When you call mosquitto_publish() it can only return success, barring any other errors. When the client attempts to send that publish, it discovers that the network is down and so any subsequent publishes will return the appropriate error.