This project provides three Java examples for learning MQTT using the Eclipse Paho MQTT client and the public test broker at test.mosquitto.org.
- Simple Publisher, Subscriber, and Publish–Subscriber (Handler)
- Uses the Eclipse Paho MQTT Client
- Demonstrates core MQTT concepts (topics, QoS, callbacks)
- Ready for students to explore and extend
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>All communication goes through the public MQTT broker:
- Broker URL:
tcp://test.mosquitto.org:1883
The handler uses two topics:
example/toIgnoreexample/toRead
The subscriber listens to both, but you can imagine example/toIgnore as background or noisy data and example/toRead as the “interesting” stream.
You are encouraged to change these topic strings and observe how behavior changes.
This is the only class you need to run to see the full publish/subscribe demo.
-
Defines the broker URL and the topics (
example/toIgnore,example/toRead) -
Creates a
Subscriberand aPublisher, each with the same broker and topics -
Starts both as independent threads so they run concurrently
-
How to run:
javac *.java
java HandlerA Runnable that connects to the broker and periodically publishes messages to the two topics given by Handler.
Conceptual behavior:
- Connects to
tcp://test.mosquitto.org:1883 - For a fixed number of iterations:
- Builds one message for
example/toIgnore - Builds one message for
example/toRead - Publishes both with a chosen QoS (e.g., 2)
- Builds one message for
- Logs each published message to the console
- Disconnects cleanly at the end
A Runnable and MqttCallback that connects to the broker and subscribes to the given topics.
Conceptual behavior:
- Connects to
tcp://test.mosquitto.org:1883 - Subscribes to both:
example/toIgnoreexample/toRead
- Implements
messageArrived(...)to print incoming messages:
📥 Connected to broker: tcp://test.mosquitto.org:1883
📥 Subscribed to: example/toIgnore
📥 Subscribed to: example/toRead
📥 Delivery :: [example/toRead : 2] :: this is message to read 0
📥 Delivery :: [example/toIgnore : 2] :: this is message to ignore 0
↗️ Connected to broker: tcp://test.mosquitto.org:1883
↗️ Published to example/toIgnore: this is message to ignore 0
↗️ Published to example/toRead: this is message to read 0
A drafted class diagram of the current release is as follows:
test.mosquitto.orgis a public broker:- Do not send sensitive or private data.
- Anyone can publish/subscribe on the same topics.
- If you don’t see messages:
- Make sure
Handleris running (both publisher and subscriber threads are started). - Check your network and any firewalls that might block port 1883.
- Confirm that the broker is online (the public test broker can occasionally restart).
- Make sure