Getting Started with MQTT — Part 2

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.

Image for post
Image for post

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 :

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

  • 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”

  • 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}”

Image for post
Image for post
Publisher publishing a message using authentication
Image for post
Image for post
Subscriber receiving the sent message
  • In case you try to connect without or incorrect username/password, you will be thrown an error :
Image for post
Image for post
Error in case of publisher
Image for post
Image for post
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.

Written by

Java Developer | CS Grad, IIIT Jabalpur

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store