Getting Started with MQTT — Part 2

Nitin Sharma
3 min readApr 16, 2019

This tutorial is second part of three-part tutorial series on “Getting Started with Mqtt” which will be a guide on setting up a MQTT server on your linux machine

Pre-requisites

Before setting up and starting to work with an MQTT server, advice is to go through some basic concepts of MQTT first.

Setting Up

Here we will be using Mosquitto as a MQTT Broker and Paho as its client on a linux system. Setting up Mosquitto in linux is simple :

Setting up a Mosquitto Broker

In your linux terminal, run following commands :

sudo apt-get update
sudo apt-get install mosquitto

This will automatically start mosquitto as a service. If it doesn’t, then run command :

sudo systemctl start mosquitto

Setting-up and Testing Mosquitto Client

  • Run in terminal to install client :

sudo apt-get install mosquitto-clients

  • In this terminal window, subscribe a client to topic “test/topic” :

mosquitto_sub -t “test/topic”

  • In another terminal window, create a publisher and publish some message and you will see this message appear in subscriber terminal.

mosquitto_pub -m “You know nothing snow” -t “test/topic”

Securing with Password

  • Mosquitto provides a password generation utility : ‘mosquitto_passwd’. Run following command to set authentication :

sudo mosquitto_passwd -c /etc/mosquitto/passwd <username>

Password: <password>

  • Create a configuration file pointing to this above created password file

sudo gedit /etc/mosquitto/conf.d/default.conf

This will open an empty “default.conf” file. Save following detail in this file and restart mosquitto :

allow_anonymous false
password_file /etc/mosquitto/passwd

  • Restart the mosquitto instance

sudo systemctl restart mosquitto

  • Now you will only be able to connect to broker using respective username and password. Updated commands for pub/sub are :

sudo mosquitto_sub -t “{topic}” -u “{user}” -P “{pass}”
sudo mosquitto_pub -t “{topic}” -m “{msg}” -u “{user}” -P “{pass}”

Publisher publishing a message using authentication
Subscriber receiving the sent message
  • In case you try to connect without or incorrect username/password, you will be thrown an error :
Error in case of publisher
Error in case of subscriber

Relevant Reads

This story covered the minimal required steps to get started with an MQTT server. Stay tuned for third part of this series which will help you in integrating MQTT based broker and client using spring-boot.

Happy Learning.

To connect with me on Linkedin click here.

--

--

Nitin Sharma

Masters, NIT Surathkal | Java Developer | Bachelors, IIIT Jabalpur