Open In App

Fundamental Features of MQTT | Set 2

Last Updated : 19 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites –

Retained Messages :
In MQTT, when clients publish messages to the broker, the retain flag is by default false. In such a case, the broker simply delivers the message to the intended subscribed client and then discards the message. But if the subscribed client is currently offline, then the client will never receive the message because it will already be discarded by the broker.

To solve this problem, the retain flag is used. Messages published with the retain flag as true will be preserved by the Broker. Hence even if a subscriber client is offline, these messages will be stored and delivered to the intended client once it comes online.

For a specific topic, the broker will store only one retained message. Hence if another message is published on the same topic with a retain flag as true, then the previous message will be replaced by the new one. This is done so that the client can get the last known value easily.

Enable and Disable Retain Messages :
To enable this functionality, the retain flag can be set along with the published message. However, retained messages cannot be disabled by setting the flag back to false. The client needs to send an empty message on the same topic with the retain flag as true to disable this functionality. The empty message does not interfere with any other communication being done on that topic and hence helps to disable the functionality efficiently.

Example –
In the example below, the sensor publishes its current value to the broker with a retained message as true. The client which is online immediately receives this message. As the retained flag is true, the broker stores the message and delivers it to the second client once it comes online. Hence due to this feature, even the offline client is updated with the most recent sensor value after it comes online.


Figure – Retained Messages


In the below illustration, the client comes online after the two message publications are completed. Hence it only receives the message published with the retain flag as true.


Figure – Mosquitto Illustration of Retained Messages


Advantages :

  • Provides the most recent status update to offline clients immediately when they come online.
  • If no new value was published on the topic, then the clients will be provided with the last known value once they come online. Hence they will know the current status of the system even when there is no new activity in the system.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads