Enabling and using WebSockets on Mosquitto

In this post, we’ll see how to enable and use the WebSocket protocol in Mosquitto to allow MQTT transmission from Javascript. A sample use of MQTT through a WebSocket is then performed.

First, the bad news. It seems that the Mosquitto package from Raspbian official repositories doesn’t include web socket support. Good news is that Mosquitto has a partner which provides packages for Raspbian (both Wheezy and Jessie). These packages support the web socket protocol.

Installing Mosquitto with web socket support

The setup is well described in Mosquitto’s blog post. For Raspbian Jessie, here what needs to be done if package was already installed :

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update
sudo apt-get dist-upgrade

When I performed dist-upgrade, apt asked me to install libwebsockets. Another way would be to remove mosquitto and install it after.

Configuring Mosquitto to support web socket connexions

Mosquitto can support to listen on several ports, each port having its own protocol. In order to enable web socket protocol, and to keep raw mqtt protocol, you need to declare both protocols.

In /etc/mosquitto/mosquitto.conf, or in a new file (ex: /etc/mosquitto/conf.d/websocket.conf) add the following lines:

listener 1883
listener 1884
protocol websockets

I set first listener to default port and didn’t specified protocol to get default mqtt protocol. Then I chose another port for web socket protocol.

Then restart Mosquitto:

sudo service mosquitto restart

Now first thing to try is that you didn’t break anything. For that, use the commands from my previous post.

A simple web client

In order to perform a simple test of the web socket protocol, we can use the Paho library provided by Eclipse. They have a Javascript implementation, so it can be used in a simple web page.

The code is pretty simple and I won’t comment it since it is a simple adaptation of the code provided on Paho’s page. Just take care to specify the web socket port, not the MQTT one.

Code source is available here: 2016-05-29_MosquittoWebSockets.

4 Replies to “Enabling and using WebSockets on Mosquitto”

  1. Thats working, thank you!
    Searched the last days to get mosquitto with websocket support working.

  2. After following the installation process. I got this after i edited my /etc/mosquitto/mosquitto.conf

    Error: Websockets support not available

    I dont get it.

  3. Hi,
    I had to chmod the file /var/log/mosquitto/mosquitto.log in order to make it work!

    Else it would fail to load the mosquitto.conf and hence websockets.conf

Leave a Reply

Your email address will not be published. Required fields are marked *