Getting started with MQTT (For client side)

Ashiq
Updated 1 Jun 2021
HIGHLIGHTS
  • Overview of MQTT
  • Setup and connect
  • Subscribe & publish model
  • Test relatime messaging

How about developing a realtime application without knowledge of socket? Introducing MQTT a Bi-directional lightweight messaging protocol used widely in IoT and many applications you use daily. Because its light weight it works seemless even with slow network as it comsumes minimal bandwidth and has capability to connect millions of devices at once. Isn't it interesting?

MQTT is an standard messaging protocol for IoT. It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth.
Source : https://mqtt.org

Before we jump into codes

Lets first understand how mqtt works. Mutliple devies are connected in a virtual mesh using a common Topic name. Devices those who want to receive data published to a topic wil first have to subscribe the topic and then when ever the publisher published message to the topic it will automatically send the message to all the clients who subscribed to the topic.

All devices are connected to a common broker which handles publish and subscribe network

What is topic name?

Topic name is a string which is formed by combination of various parameters like domain + project name + publisher + subscriber, it can be any string but to keep things organised we should choose a meaning full topic name

Who is broker?

Our server which listens on xyz port that is responsible for managing the mesh of all devices.

Who is publisher?

Any client that sends/broadcasts the message is publisher

Who is subscriber?

Any client that want to receive message published to a particulat topic is a subscriber

Layman way : Suppose your email ID is the topic, so if you open you email account in multiple devices and someone sends you an email all the devices where you logged in will receive the email. Similarly if you want to send email you will write an email and send the email to some xyz email ID and that xyz email ID will receive the email.

Who should keep reading?

If you have bit knowledge of html, javasvript and want to try realtime messaging and delolop client side application with relatime communication then its for. If you are lookgin for server side implemention this post is not for you.

Enough theory, lets jump into coding. We will be using third party availble MQTT brokers to test the functionality of how realtime communication works.

Overview

  1. We will create a form to publish messsage
  2. Setup mqtt connection
  3. Connect, then subscribe to a topic
  4. Handle incoming message
  5. Create a function to publish message
  6. Test by sending messages from multiple devices


Baisc HTML code to enter and display messages

<body onload="connect()">
	<input id='message'>
	<button onclick="publish()">SEND</button>

	<div id="window"></div>

	<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
	<script src="mqtt.js"></script>
</body>

Basic configuration before connecting

//the host to which we want to connect
const host = "test.mosquitto.org";
const port = 8080;//port number the host is listening to
//our topic to publish and receive message
const topic = "guest.com/cdfe45dgbhf9/user/all";
//variable to hold connection data
let client;

Lets try connecting

function connect(){
	try{
		// create a client instance, 
		// "" is client id, if empty string is passed a random client id will be generated
		client = new Paho.MQTT.Client(host, port, "");

		// will be called when new message arrives
		client.onMessageArrived = onMessage;

		//when connection is lost
		client.onConnectionLost = function(){console.log('Connection lost')};

		// lets connect the client
		client.connect({
			onSuccess : () => {
			    console.log("connected");
			    
				// subscribe to the topic, we will publish message to this topic
				client.subscribe(topic);
			},
			onFailure : () => {
				console.log("failed to connect");
			}
		});
	}
	catch(err){
		console.log(err);
	}
}

Function to handle incomming messages

function onMessage(mgs){
	//parse the received message
	mgs = JSON.parse(mgs.payloadString);
	let html = document.getElementById('window').innerHTML + `<div>${mgs.m}</div>`;
	//append html to DOM
	document.getElementById('window').innerHTML = html;
}

Function to publish a message

function publish(){
	//get message form input box
	let m = document.getElementById('message').value;

	//prepare the payload
	let data = JSON.stringify({m});
	let mgs = new Paho.MQTT.Message(data);
	mgs.destinationName = topic;
	//publish from here
	client.send(mgs);
	
	document.getElementById('message').value = '';
}


Entire mqtt.js script

const host = "test.mosquitto.org";

//try 8080,8081,1883,1884
const port = 8080;
const topic = "guest.com/cdfe45dgbhf9/user/all";
let client;


function connect(){
	try{
		client = new Paho.MQTT.Client(host, port, "");

		client.onConnectionLost = function(){console.log('Connection lost')};
		client.onMessageArrived = onMessage;

		client.connect({
			onSuccess : () => {
			  console.log("connected");
				client.subscribe(topic);
			},
			onFailure : () => {
				console.log("failed to connect");
			}
		});
	}
	catch(err){
		console.log(err);
	}
}


function onMessage(mgs){
  	mgs = JSON.parse(mgs.payloadString);
  	let html = document.getElementById('window').innerHTML + `<div>${mgs.m}</div>`;
  	document.getElementById('window').innerHTML = html;
}


function publish(){
	let m = document.getElementById('message').value;

	let data = JSON.stringify({m});
	let mgs = new Paho.MQTT.Message(data);
	mgs.destinationName = topic;
	client.send(mgs);

	document.getElementById('message').value = '';
}



In action, realtime messaging from two different browser


PS : Since I used public mqtt broker in this post so those are not accessible from webpages servered via https. Its always recommended to setup own mqtt broker or we can also use AWS MQTT which is quite cheap.

Go guys, build your dream realtime projcet with MQTT

If you want me to write post on setting up own mqtt broker on server do let me know


Additional resources

  1. Download code - Github
  2. Paho MQTT documentation
  3. mqtt.org