How to test Persistent Session Management with MQTT Brokers

This article guides users on initiating and managing persistent sessions with MQTT brokers, using either HiveMQ Cloud or another broker. Persistent sessions ensure uninterrupted communication, even when subscribers temporarily disconnect. Below are the steps to set up and maintain a persistent session through the command line.

Instructions

Prerequisites:

Before proceeding, ensure the following prerequisites are met:

  1. You have read and understand how persistent sessions work :

  2. MQTT Broker:

    • If using HiveMQ Cloud, create valid credentials (username and password) and note the broker URL.

    • If using another broker, ensure you have the necessary credentials and connection details.

  3. MQTT Command-Line Tools:

    Note: Download and install MQTT command-line tools from the official MQTT GitHub repository. Ensure compatibility with your system's JDK.

Creating a Persistent Session:

To start a persistent session, use the following command in the terminal:

mqtt subscribe --identifier 'MySubscriber' --topic '#' --qos 1 \ --sessionExpiry 3600 --no-cleanStart \ --host ${your_broker_url} --port 8883 --secure \ --user ${your_user_for_subscriber} --password ${your_password_for_subscriber}

 

This command subscribes to the specified topic (# for all topics), assigns an identifier to the subscriber (MySubscriber), sets the session expiry time to 3600 seconds, and ensures a non-clean start. Replace ${your_broker_url}, ${your_user_for_subscriber}, and ${your_password_for_subscriber} with your MQTT broker's URL, username, and password.

Interrupt the session by pressing Ctrl+C.

Publishing a Message While Subscriber is Offline:

To publish a message while the subscriber (MySubscriber) is offline, use:

mqtt publish --topic Test --message Hello --qos 1 \ --identified MyPbulisher \ --host ${your_broker_url} --port 8883 --secure \ --user ${your_user_for_publisher} --password ${your_password_for_publisher}

 

This publishes the message "Hello" to the specified topic (Test). The message queues until the subscriber reconnects.

Restoring the Session:

To restore the session, use the following command:

mqtt subscribe --identifier MySubscriber --topic '#' --qos 1 --showTopics \ --sessionExpiry 3600 --no-cleanStart \ --host ${your_broker_url} --port 8883 --secure \ --user ${your_user_for_subscriber} --password ${your_password_for_subscriber}

 

Ensure the same identifier (MySubscriber) and --no-cleanStart flag is used to restore the previous session.

Check if the subscriber received queued messages. The persistent session retains messages sent while offline.

Conclusion:

Managing persistent sessions with MQTT brokers, whether HiveMQ Cloud or another, ensures uninterrupted communication. Follow the provided commands to initiate, interrupt, and restore MQTT sessions, ensuring continuity in message delivery. Adjust parameters based on your specific MQTT broker details.