Skip to content

MQTT Web Applications: How to Build Your Own!

by HiveMQ Team
5 min read

Why Should I Use WebSockets With MQTT

With the new features introduced with HTML5 you can now even build websites which behave like a native desktop applications and work on tablets and smartphones the same way they do on a desktop computer. So using a browser like any app on any other mobile device is a very tempting idea. A browser is installed on nearly every desktop computer/laptop/tablet/smartphone around the world. And honestly wouldn’t it be nice if you could use one standardized protocol to get real push messages on all types of devices, browsers, tablets, smartphones, embedded devices, sensors, etc. The protocol you are looking for is MQTT and it is very simple and quick to implement.

How to Use MQTT With WebSockets

For a simple websockets client, which subscribes and publishes to a MQTT Broker, there are very few steps involved to get it up and running. It is actually pretty simple because there is a very good library available that already does most of the work for you, the Paho Javascript client.

To check that your code is working you can use the HiveMQ Websocket MQTT Client and publish/subscribe to the same MQTT topics as in the example code.

And if you don’t want to setup your own MQTT broker you can always use the public HiveMQ broker from the MQTT-Dashboard.

Connecting an MQTT Broker

First of all, we want set up a connection to the MQTT Broker. This is done by creating a Messaging.Client Object and calling the connect method with a set of options.

//Create a new Client object with your broker's hostname, port and your own clientId
var client = new Messaging.Client(hostname, port, clientid);

var options = {

     //connection attempt timeout in seconds
     timeout: 3,

     //Gets Called if the connection has successfully been established
     onSuccess: function () {
         alert("Connected");
     },

     //Gets Called if the connection could not be established
     onFailure: function (message) {
         alert("Connection failed: " + message.errorMessage);
     }

 };

//Attempt to connect
client.connect(options);

Subscribe to an MQTT Topic

Subscribing to one or more topics is done by a simple call to the subscribe method of the client

client.subscribe("testtopic", {qos: 2});

Publish to an MQTT Topic

Publishing to a specific topic requires you to create a Messaging.Message object and pass it to the publish method of the client

var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
client.send(message);

Demo

You can start the fullscreen demo or play with the JSFiddle.

Note: If you instantly see a few messages after you hit the subscribe button, these are so called retained messages. This means that the last message which has been sent to the broker for this topic which had the retained flag set will be persisted on the server and sent to every new subscriber to this topic. A pretty nice extra if you always want to have access to the last sensor reading that was published to the broker for example.

Additional Goodie

A very cool feature of MQTT is the ability to specify a so called Last-Will-And-Testament Message and Topic. Whenever a connection gets disconnected unexpectedly the broker will publish a message to a topic which was specified by the client on connect. In the websocket scenario this allows you to act on a closed tab/browser by reacting to the LWT message which was sent by the broker. You can set the LWT topic, message, etc. by passing additional properties in the options for the connect method.

var willmsg = new Messaging.Message("My connection died");
willmsg.qos = 2;
willmsg.destinationName = "willtopic/machine5";
willmsg.retained = true;
options.willMessage = willmsg;

client.connect(options);

HiveMQ Team

The HiveMQ team loves writing about MQTT, Sparkplug, Industrial IoT, protocols, how to deploy our platform, and more. We focus on industries ranging from energy, to transportation and logistics, to automotive manufacturing. Our experts are here to help, contact us with any questions.

Related content:

HiveMQ logo
Review HiveMQ on G2