Reader small image

You're reading from  Practical Python Programming for IoT

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838982461
Edition1st Edition
Languages
Right arrow

Publishing a retained message

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:

  1. 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.
  1. 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...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020Publisher: PacktISBN-13: 9781838982461