Setting Up MQTT Broker on Linux and Windows

Some commonly used MQTT brokers are Mosquitto, EMQTT, and HiveMQ. HiveMQ is not open-source and has a fee, so it may not be suitable for local testing. EMQTT has powerful features, such as viewing data traffic on a web interface, and can be used on most cloud servers, with both free and paid custom versions available.

This section focuses on how to use Mosquitto to set up an MQTT broker on Windows or Linux. Mosquitto is an open-source (EPL/EDL licensed) message broker that implements MQTT protocol versions 5.0, 3.1.1, and 3.1. It is considered a lightweight open-source software. The Mosquitto project provides a C language library for implementing MQTT clients and popular command-line MQTT clients mosquitto_pub and mosquitto_sub. Besides, Mosquitto can also be used as an MQTT broker. For more information, please refer to its official website.

Setting up MQTT broker on Linux

All terminal commands in this section must be run in the user role. The $ symbol represents the command prompt.

  1. Download mosquitto-2.0.12.tar.gz from https://mosquitto.org/files/source.

  2. Extract Mosquitto.

    $ tar -zxvf mosquitto-2.0.12.tar.gz

    Check if the installation is successful using mosquitto --help.

    $ cd mosquitto-2.0.12/src
    $ mosquitto --help
    mosquitto version 2.0.12
    mosquitto is an MQTT v5.0/v3.1.1/v3.1 broker. 
        Usage: mosquitto [-c config_file] [-d] [-h] [-p port]
            -c : specify the broker config file.
            -d : put the broker into the background after starting.
            -h : display this help.
            -p : start the broker listening on the specified port. Not recommended in conjunction with the -c option.
            -v : verbose mode - enable all logging types. This overrides any logging options given in the config file.
            See https://mosquitto.org/ for more information.
  3. Start MQTT broker and test in the MQTT client.

    a. Start MQTT.

    $ mosquitto

    b. Use mosquitto_sub to subscribe to topic.

    $ mosquitto_sub -t 'test/topic' -v

    c. Open a new terminal and use mosquitto_pub to publish data.

    $ mosquitto_pub -t 'test/topic' -m 'hello world'

    d. In the original terminal where the topic was subscribed, view the received data.

    $ mosquitto_sub -t 'test/topic' -v
    test/topic hello world

Setting up MQTT broker on Windows

  1. Download the 32-bit or 64-bit MQTT installation package based on your computer's architecture. Double-click to install it.

  2. Open a command prompt window, navigate to the directory where Mosquitto is installed, and start the Mosquitto broker.

    cd C:\Program Files\mosquitto\
  3. Use mosquitto_sub.exe to subscribe to topic.

    C:\Program Files\mosquitto>mosquitto_sub.exe -t 'test/topic' -v
  4. Use mosquitto_pub.exe to publish data.

    C:\Program Files\mosquitto>mosquitto_pub.exe -t 'test/topic' -m 'hello_world'