MQTT Web Applications: How to build your own!
Written by The HiveMQ Team
Published: September 24, 2013
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
To check that your code is working you can use the HiveMQ Websocket MQTT Client and publish/subscribe to the same 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.
Subscribe to an MQTT Topic
Subscribing to one or more topics is done by a simple call to the
subscribe method of the
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
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.
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