Hello MQTT – Basic Message Publishing/Subscribing

Your first steps into real-time IoT messaging with Python and Mosquitto.

Download PDF

Abstract

Ever wanted your devices to talk to each other like old friends? This guide introduces you to the basics of MQTT messaging using the Mosquitto broker and Python's Paho MQTT library. Whether you're on Windows, Linux, or macOS, this is your beginner-friendly path to understanding how devices communicate in the Internet of Things.

Guide Contents

Software Requirements:
Python 3, Paho-MQTT library, and Mosquitto broker.
This section describes what each tool does and how to install them.

Component Description
Python 3 Programming language for our scripts
Paho-MQTT Python library to connect to MQTT brokers
Mosquitto Lightweight MQTT broker (local testing)

🐧 Linux (Ubuntu/Debian):


          sudo apt update
          sudo apt install mosquitto mosquitto-clients
          sudo apt install python3 python3-pip
          pip3 install paho-mqtt==1.6.1
                

πŸͺŸ Windows:

  • Download Mosquitto from mosquitto.org/download
  • Install with default settings (ensure port 1883 is allowed in Windows Firewall).
  • Add mosquitto to your system PATH or run it from the install directory.
  • Install Python & pip from python.org
  • Install the correct Paho MQTT version:

          pip install paho-mqtt==1.6.1
                

🍎 macOS (with Homebrew):


          brew install mosquitto
          brew services start mosquitto
          pip3 install paho-mqtt==1.6.1
                

MQTT Flow Diagram:


Publisher.py  β†’  MQTT Broker (Mosquitto)  β†’  Subscriber.py
                

1️⃣ Start the Mosquitto Broker
On Linux/macOS:


mosquitto -v
                

On Windows:


"C:\Program Files\mosquitto\mosquitto.exe" -v
                

2️⃣ Create the Publisher Script


import paho.mqtt.client as mqtt
import time

broker = "localhost"
publisher = mqtt.Client("Publisher")

publisher.connect(broker, 1883)

try:
    while True:
        publisher.publish("biot/test1", "Hello from BIoT!")
        print("Message sent.")
        time.sleep(2)
except KeyboardInterrupt:
    print("Stopped by user.")
finally:
    publisher.disconnect()
                

3️⃣ Create the Subscriber Script


import paho.mqtt.client as mqtt

def on_message(client, userdata, message):
    print(f"Received: {message.payload.decode()}")

broker = "localhost"
subscriber = mqtt.Client("Subscriber")

subscriber.connect(broker, 1883)
subscriber.subscribe("biot/test1")

subscriber.on_message = on_message
subscriber.loop_forever()
                

4️⃣ Run & Test
Terminal 1:


python subscriber.py
                

Terminal 2:


python publisher.py
                

Expected:


Received: Hello from BIoT!
Received: Hello from BIoT!
...
                

🧩 Issue 🧰 Solution
ConnectionRefusedError when running Python script Make sure the Mosquitto broker is running. Try : mosquitto -v or check the Task Manager (Windows) for mosquitto.exe.
Port 1883 already in use or Only one usage of each socket address... Mosquitto is already running. Don't start it again. If needed, restart your machine or stop the existing service.
Publisher/Subscriber not receiving messages Ensure both scripts are using the same topic (e.g., biot/test1) and the correct broker address (localhost or IP).
Python can't find paho.mqtt Install the correct version: pip install paho-mqtt==1.6.1. Avoid newer versions unless you handle callback_api_version.
ValueError: Unsupported callback API version This happens with paho-mqtt >= 2.0. Fix by downgrading to version 1.6.1: pip install paho-mqtt==1.6.1
Mosquitto not starting on Windows Right-click and run as Administrator. Also, ensure Windows Defender Firewall allows access to port 1883.
Can't connect using localhost Try using 127.0.0.1 instead. In some systems, localhost may not resolve properly.

Future Scope & Next Steps:

  • πŸ” Secure MQTT with TLS/SSL
  • πŸ§‘β€πŸ’» Use real IoT devices (ESP32, Raspberry Pi)
  • πŸ“Š Visualize data with Node-RED or web dashboard
  • πŸ” Explore MQTT QoS and retained messages