A publisher can ask the broker to retain a message as the last known good message for a topic. Any newly connecting subscriber will immediately receive this last retained message.
Let's step through an example to demonstrate retained messages:
- Run the following, noting that we're starting with Terminal #2, the publisher in this example:
# Terminal 2 (Publisher)
$ mosquitto_pub -r -q 2 -h localhost -t 'pyiot' -m 'hello, I have been retained!'
A new option has been added,-r (--retain), to tell the broker that this message should be retained for the topic.
Only a single retained message can exist for a topic. If you publish another message using the -r option, the previous retained message will be replaced.
- Start a subscriber in another Terminal, and immediately you will receive the retained message:
# Terminal 1 (Subscriber)
$ mosquitto_sub -v -q 2 -h localhost -t 'pyiot'
pyiot hello, I have been...