Using MQTT Over WebSockets with Mosquitto

What is Websockets and How it Works?

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP/IP connection. Wiki

It is closely associated with http as it uses http for the initial connection establishment..

The client and server connect using http and then negotiate a connection upgrade to websockets, the connection then switches from http to websockets.

The client and server can now exchange full duplex binary data over the connection.

Video -MQTT Over Websockets Explained

 

Why Use MQTT over Websockets?

MQTT over Websockets allows you to receive MQTT data directly into a web browser.

This is important as the web browser may become the DE-facto interface for displaying MQTT data.

MQTT websocket support for web browsers is provided by the JavaScript client.

MQTT Over Websockets vs MQTT.

In the case of MQTT over Websockets the websockets connection forms an outer pipe for the MQTT protocol.

The  MQTT broker places the MQTT packet into a websockets packet, and sends it to the client.

The client unpacks the MQTT packet from the websockets packet and then processes it as a normal MQTT packet.

This is illustrated in the diagram below:

MQTT-websockets-illustration

With MQTT the MQTT Packet is placed directly into the TCP/IP Packet.

Websockets and Mosquitto

The default Mosquitto install packages for Windows and Linux both support WebSockets.

Very early versions 1.4.x needed to be compiled with websocket support. This is no longer necessary.

Websockets on Windows

Since mosquitto 1.5.1 websockets support has been enabled on the windows binary files.

However when you start mosquitto it appears to be listening on the websocket port but doesn’t allow connections.

mosquitto v 1.5.4 does work with websockets. Here is a link for the downloads.

Configuring Websockets On Your Own Mosquitto Broker

MQTT over Websockets usually uses port 9001 but it isn’t fixed.

You need to make change to the mosquitto.conf file, by adding the following:

listener 9001
protocol websockets

This creates an extra listener using websockets and port 9001.

When you start the broker you should see something like this:

mosquitto-websockets

Testing Websockets

To test websockets you will need a client that supports websockets.

Here we look a using both the paho python client and the paho Javascript client.

Websockets and the Python Client -Example

To tell the client to use websockets instead of MQTT use the command

client= paho.Client(“control1”,transport=’websockets’)

instead of simply

client= paho.Client(“control1”)

When creating a new MQTT client object.

You also need to set the port to the WebSocket port. (9001).

Here is a Python demo script that you can use to publish and subscribe using websockets.

If you run the script you see:

web-socks-pub-sub-python

There is no real indication that the client is using websockets as opposed to standard MQTT.

Video

JavaScript Web Browser Client

The client is meant to be run in a browser and so you need to create a web page and add your JavaScript code.

See this tutorial- Understanding and using The JavaScript MQTT Client With Websockets for detailed usage examples, scripts and download links.

Here is a link to the MQTT websockets Javascript docs

Videos

Using Websockets over TLS (SSL)

To use websockets over TLS you need to configure the broker to use TLS.

See this tutorial Mosquitto SSL Configuration -MQTT TLS Security.

Now we edit our mosquitto.conf file. It should look like this:websockets-ssl-config-mosquitto

Notice The extra listener is using websockets and the ssl configuration applies to it. I also used port 8081.

On the Python client add the client.tls_set() command to tell it to use SSL as well as setting the transport.:

client= paho.Client("control1",transport='websockets')

client.tls_set('c:/python34/steve/mqtt-demos/certs/ca.crt')

Using an External MQTT Broker with Websockets

If you can’t get websockets on your own broker then you can use as external one like :

  • test.mosquitto.org– uses port 8080 un-encrypted and 8081 for websockets over SSL.
  • iot.eclipse.org support only encrypted and uses port 443 for websockets over SSL..
  • broker.hivemq.com -uses port 8000 for websockets. Websockets over SSL not supported.

Here is a list of other test brokers with Port numbers

Testing Tools

The mosquitto_pub and mosquitto_sub tools do not support websockets.

The MQTT box (Google Chrome extension) tool supports both websockets and secure websockets. However you may have difficulty with SSL if you use your own CA.

MQTTLens supports websockets but not secure websockets.

Common Questions and Answers

Q- Can You use websockets over an encrypted connection?

A- Yes

Q- Are there two JavaScript Clients?

A- Yes the one uses MQTT over Websockets and is meant to be run in a browser. The other uses MQTT and is meant for use with node.js.See Using the Node.js MQTT Client-Starting Guide



Reported Issues

 

You may recall last month a I had a few questions and issues with Javascript websocket connections to mosquitto broker. – every time I connected using the javascript over websockets  – the esp8266 would disconnect.

I was using the windows mqtt Mosquitto broker version 2.03.

It seems that on 22 december 2020 and new version was released ( v2.0.4) an it indicated a bug fix  –

” – Fix websockets connections blocking non-websockets connections on Windows.”

so I installed that new version… and it now works perfectly ….

Related Tutorials and resources

Please rate? And use Comments to let me know more

94 comments

  1. Greetings,

    Thanks for making these guides, they are very helpful.
    I have come across an issue using Mosquitto 2.0.13 on windows 10.

    When ever I add a listener with protocol websocket my broker does not start. I also do not see anything useful logging in the log file.

    My config file :

    per_listener_settings true
    log_dest file c:\log\mosquitto.log
    log_type all
    connection_messages true
    log_timestamp true
    log_timestamp_format %Y-%m-%dT%H:%M:%S

    listener 1883
    protocol mqtt
    allow_anonymous true

    listener 9001
    protocol websockets
    websockets_log_level ff
    allow_anonymous true

    This is all I can see in the log file:

    2021-11-18T17:52:13: mosquitto version 2.0.13 starting
    2021-11-18T17:52:13: Config loaded from C:\Program Files (x86)\mosquitto/mosquitto.conf.
    2021-11-18T17:52:13: Opening ipv4 listen socket on port 1883.
    2021-11-18T17:52:13: Opening websockets listen socket on port 9001.

    If I start the service it stops, if I start it manually it stops.

    If I disable the websocket listener it works.
    I did an exhaustive search on the web without finding anything useful.

    Any thoughts?

    Cheers,
    F

    1. I tried it and it started bu I couldn’t connect to it with websockets. I dropped back to 2.10 and it worked OK.
      Rgds
      Steve

      1. Hi Steve,

        I have given up on using the mosquitto broker as service. Manually starting it seems to do the trick.
        I dont know why.

        I came across another problem. Accessing my server from outside my local network. After many hours of fiddling, googling and trying to get access. I eventually saw that there is no listing happening on my netstat /a on the port I specified. In any case, it seems if you do not explicitly tell it to use socket_domain ipv4, it actually only listens on ipv6. When I added that , I could easily access my broker via html from outside.

        Cheers F

  2. Im using a Raspberry Pi as a web server and using mqtt with port 1883 and port 9001
    When I open the webpage on my local network it works fine but outside of my local network it fails
    with Uncaught ReferenceError: MQTTconnect is not defined
    Im using as3935_mqtt = new Paho.MQTT.Client(host, 9001, “web_as3935”); which Im assuming is the problem but why does it fail with the above MQTTconnect is not defined when outside of my network
    Appreciate any help
    Phil

    1. It is probably not accessing the mqtt script which needs to be downloaded from the internet.
      If you send me a copy of the script I will take a look.
      Also do you port forwarding set up so you cna access your broker from outside the local network?
      Rgds
      Steve

        1. Hi Steve
          Thanks for your patience
          I was using one of your examples so I must be doing something wrong its :

          JavaScript MQTT WebSocket Example

          var mqtt;
          var reconnectTimeout = 2000;
          var host=”192.168.1.163″; //change this
          var host=”192.168.1.145″;
          //var host=”steve-laptop”; //change this
          // var host=”localhost”;
          var port=9001;
          //var port=9001;
          //var port=8881;

          function onConnect() {
          document.write(“Connected”);
          // Once a connection has been made, make a subscription and send a message.

          console.log(“Connected “);
          //mqtt.subscribe(“sensor1”);
          // message = new Paho.MQTT.Message(“Hello World”);
          // message.destinationName = “sensor1”;
          // mqtt.send(message);
          }

          function MQTTconnect() {
          console.log(“connecting to “+ host +” “+ port);
          var x=Math.floor(Math.random() * 10000);
          var cname=”orderform-“+x;
          mqtt = new Paho.MQTT.Client(host,port,cname);
          document.write(“connecting to “+ host);
          var options = {

          timeout: 3,
          onSuccess: onConnect,

          };

          mqtt.connect(options); //connect
          }

          Main Body

          MQTTconnect();

          When I open this page on my local network I get “Connected” on the web page but on the network I just get “Connecting to 192.168.1.145”
          Sorry I must be doing something daft
          Port 9001 has been port forwarded on my router using https://www.yougetsignal.com/tools/open-ports/
          Phil

          1. Phil
            If it works in the local network then the only thing stopping from working outside the network is your firewall.
            Have you opened port 9001 on the fire wall see here for details
            https://stevessmarthomeguide.com/understanding-port-forwarding/
            The error message is a bit misleading unless for some reason it cannot access the mqttclient script when outside the fire wall.Check this line at the top of the script that it isn’t using a local copy

            JavaScript MQTT WebSocket Example

  3. Thank you for the informative articles – greatly appreciated.

    However: This page is right at the top of search results on Mosquitto, Websockets and Windows. I followed it, saw the highlighted information (“Windows install packages still don’t have websockets”) and wasted a lot of time pursuing other options.

    Turns out you were too sloppy to remove obsolete information…. Very annoying. PLEASE do everyone a favour and fix it.

    1. Hi
      Took a look. There was a note on windows that it works in 1.5.4.
      The compile information was left as reference but I’ve removed it to avoid confusion.
      Rgds
      Steve

  4. Hi Steve!

    This is my config file:

    per_listener_settings true
    allow_anonymous false
    password_file C:\Program Files\Mosquitto\p2.txt
    listener 9001
    protocol websockets

    When i use Mqtt Exploreer tool to connect by websocket, the broker respond: Connection refused: Not authorized.

    What is wrong in the config file?

    1. The broker wants a valid user name and password.
      Try commenting out the password file and set allow_anonymous to true and get that working first
      rgds
      steve

      1. Hello Steve , thanks for this helpful topic. I have a problem in using mqtt over websockets. I’m using a raspberry pi as a host server for several tools such as mosquitto broker,node red, influx db, and grafana. I’m trying to use grafana to control a sonoff switch through mqtt. I found this plugin: https://github.com/geeks-r-us/mqtt-panel
        that allows grafana to communicate with an mqtt server. I have installed the plugin but i can’t connect it to the broker! In the plugin’s GitHub page the author have mentioned a limitation says ” Due to the MQTT client runs in the browser it can only establish mqtt connection over websockets and can only connect to servers reachable by your browser.”
        Could you tell me how to establish this connection ?!

  5. Thank you for the answer, Steve. Does the MQTT client / Server requires IP address for communication?

  6. Hi Steve,
    I am new to this MQTT protocol and your tutorial helped me a lot to understand it. I got to understand that the cars communicate to the cloud through MQTT protocol but I am wondering whether it uses MQTT over Websocket for establishing the communication between the In-Car applications like Navigation App, Google Maps, etc to the Cloud?
    Could you please provide your suggestions

    1. Hi
      If you are talking about apps on a smart phone then I would imagine that the use http and/or websockets. MQTT over websockets would then be the logical next step.
      Rgds
      Steve

  7. Hi Mr. Steve.
    I am beginner for this works. I will try to collect data and i will write data to esp8266 by web interface. I thought install Django, Python, Mosquitto MQTT Broker to web server for creating interface for customer.
    My mind confused.
    My Question: I will do pub. / sub between web server & esp8266.
    Which one is useful Mosquitto MQTT on Websockets or Just MQTT Broker ?
    What is advantages & disadvantages e.g. speed, security, easy to making , flex improving ?
    I would be glad if you enlighten me with your suggestions and opinions.
    Best Regards…

    1. You always will need a mqtt broker if you are using mqtt. MQTT over websockets is necessary when you want to use a browser with MQTT.
      A broker will support both MQTT and MQTT over websocekts.
      As regards security you can use SSL on both.
      As for speed I have never done any testing but wouldn’t expect a great difference.
      Rgds
      Steve

      1. Users will need a web page to login and control the necessary info of IoT devices. Actually I started to think that websockets may useful for showing data on private page of user by directly when I read the information you share( Thank you for your effort to keep us informed again.
        I planned to use Django for Users. However Websokets it may make my job is easier.
        Would you use it in such a situation? I would like to know your suggestion as you have a lot of experience. I value your opinions.
        Best regards…

  8. hello Steve,
    I’m building a project I have developed all the hardware and the communication is through MQTT. The broker is installed in my windows. now I want to develop a website or web application which will have all the interface of my project I want to make it simple for a user, like On/Off button for a bulb. how should i start and which platform should I choose?

      1. thanks for the response, I used your demo pages. they are working fine with the cloud testing brokers such as test.mosquitto.org port but are not working on my local mosquito broker which is running on windows. which port should I listen to and how do I edit the config file. can you send me yours?

        1. You just need to add the following to the config file
          listener 9001
          protocol websockets

          On windows the config file is large and is all commented out so create a new one websockets.conf and use that for testing.

  9. Steve:
    I am running the standard mosquitto client on raspberry pi2b with a newly installed Raspberry Pi OS. I wanted to tell you that websockets is built in. I didn’t need to recompile and install mosquitto as this tutorial says. I just added the following lines to end of my /etc/mosquitto/mosquitto.conf file:

    listener 1883
    listener 8080
    protocol websocket

    Then I rebooted and used your example .htm(editing it to point to my MQTT) file and it just worked.

  10. Hi Steve, I want to set up an MQTT client on a network that I do not have admin access to, can I use MQTT over WSS and configure the port to 443 to get through through router firewall? (I cannot configure port access on the router.

      1. Thank you for your response, the broker is located on my local network, the clients are on farms in my surrounding area. I have the ssid and key for these networks but am unable to configure the routers.

  11. Hi, i’m working with raspbian and the configuration file mosquitto.conf looks like this:

    # Place your local configuration in /etc/mosquitto/conf.d/
    #
    # A full description of the configuration file is at
    # /usr/share/doc/mosquitto/examples/mosquitto.conf.example

    pid_file /run/mosquitto/mosquitto.pid

    persistence true
    persistence_location /var/lib/mosquitto/

    log_dest file /var/log/mosquitto/mosquitto.log

    include_dir /etc/mosquitto/conf.d
    port 1883
    listener 9001
    protocol websockets

    i added the last three lines to enable websocket but when i do that, the broker doesn’t work anymore, it shows this error:
    Connection error: Connection Refused: not authorised.
    Error: The connection was refused.

  12. Hi Steve, do we need to install or configure the SSL and WebSocket in both party (MQTT client= laptop and MQTT Broker = Mosquitto raspberry pi)? Because I want to use MQTTLens but WebSocket is needed for the connection right? So I do need to set up the SSL and the Websocket?

    Thank you in advance

      1. Thank you for the response Steve, but I want to connect my own raspberry pi (using Mosquitto) and to connect with the phone. I tried with modem and try to set wifi access in the raspberry pi but all end up with error. Because I used switch and use raspberry pi own local network for laptop (LAN cable and can connect) and phone (still cannot link the broker)

        SO I found about Websoket and MQTTLens where they connect between MQTT Client and the broker. but so far the example use online broker for the connection.

        1. You can configure mosquitto to support websockets it is just a few lines in the config file and is covered in the tutorial. I’m not sure what you mean by phone is the phone using wi-fi?

          1. When we configure the WebSocket in the raspberry pi (server), then in the MQTTLens just put the broker IP address right for the connection?

            I want to connect the phone using IoTMQTTPanel application with the server. To do that I need to make them in one network right? So what I do is I set up a hotspot in the raspberry pi so the phone can connect in their own local network.

          2. They can be on separate networks as long as they have IP connectivity it will work.
            Rgds
            Steve

  13. Hi Steve, I have tried to do this tutorial but sadly I am meeting some speed bumps.
    After editing the Mosquitto.conf file, I have added several things listener 9001, protocol websockets, allow_anonymous true. When I do:

    $sudo mosquitto -v /etc/mosquitto/mosquitto.conf
    : I get an an error: unknown option /etc/mosquitto/mosquitto.conf

    But strangely when I do

    $netstat -a
    I do find listener port 9001 with the state LISTEN.

    Kinda confused if that’s because I edited the main mosquitto.conf or if its because of some other download.

    I didn’t do the steps to download web sockets because the new mosquitto version has them installed so I just skipped and only installed the broker and configured the .conf

    any advice on what should I be looking for to get it working? Should I downgrade the mosquitto software?

    Thank you!

    1. Fot testing leave the /etc/mosquitto/mosquitto.comf file alone. Create your own file in the local folder and start mosquitto using mosquitto -c filename -v
      From the error it looks like you have a simple error in the file post the file provided it isn’t huge and i’ll take a look

      1. Thanks for the suggestion, it worked but then it said that it was unable to create Websockets listener on port 9001.

        I changed to 8083/8080 but it didn’t work so far
        ———————————————————————————————————————————————-
        I think it would be more clearer if I’d walk you through my process,

        After changing the .conf (my file) I restarted mosquitto using $sudo systemctl restart mosquitto

        and reran the command again $sudo mosquitto -c /etc/mosquitto/conf.d/default.conf -v

        To know a bit more, I added in into the “default.conf” in addition to the listener 9001/websockets

        log_type all
        websockets_log_level 255

        and got this in terminal;

        0: mosquitto version 1.5.7 starting
        0: Config loaded from /etc/mosquitto/conf.d/default.conf.
        0: Opening websockets listen socket on port 9001.
        0: Initial logging level 255
        0: Libwebsockets version: 2.0.3 unknown-build-hash
        0: IPV6 not compiled in
        0: libev support compiled in but disabled
        0: libuv support compiled in but disabled
        0: LWS_DEF_HEADER_LEN : 1024
        0: LWS_MAX_PROTOCOLS : 5
        0: LWS_MAX_SMP : 32
        0: SPEC_LATEST_SUPPORTED : 13
        0: sizeof (*info) : 160
        0: SYSTEM_RANDOM_FILEPATH: ‘/dev/urandom’
        0: default timeout (secs): 20
        0: Threads: 1 each 1024 fds
        0: mem: context: 40456 bytes (36360 ctx + (1 thr x 4096))
        0: mem: http hdr rsvd: 67968 bytes (1 thr x (1024 + 3224) x 16))
        0: mem: pollfd map: 8192
        0: mem: platform fd map: 4096 bytes
        0: Compiled with OpenSSL support
        0: Creating Vhost ‘default’ port 9001, 3 protocols
        0: Using non-SSL mode
        0: ERROR on binding fd 7 to port 9001 (-1 98)
        0: Failed to create default vhost
        0: Error: Unable to create websockets listener on port 9001.

        I believe the issue starts with “ERROR on binding fd 7 to port 9001 (-1 98).” I researched it that error 98 is caused because of the port being already in use, and using sudo lsof -i:9001 it showed that its user is mosquitto. Should I kill the process?

        Not quite sure what my next steps are, and thank you once again for the help!

          1. Hi Steve, quick update got it working, all good. I stopped and started the mosquitto process again.

            Cheers

  14. Just a quick question: I have difficulties getting it running on an iPad using Safari. Any know constraints regarding mqttws31.js for Safari / iPad?

      1. I realized that there are no special restrictions on the iPhone or iPad. It was all about trusting the certificates. I solved by the following steps:

        1. Installing the CA certificate (which is used in the Mosquitto config as cafile) onto the iPhone or iPad. You can easily do this e.g. by downloading the certificate via Safari from any location from where you want to share it. The device is then automatically asking for installation.
        2. Activate trusting the certificate on the device in Settings > General > About at the bottom.

        Then secured WebSocket connections will be accepted by the device. Ensure, that you have to use secured WebSocket protocol (wss), when the website itself is opened via https/SSL. Ensure you’re activating the useSSL: true option flag before calling MQTT.connect() in your JS code.

        Cheers,
        Armin

  15. Hi,
    I’ve got difficulties getting SSL running for websockets. Using mosquitto 1.6.12 on a Windows Server 2019 listening on ports 1883 (MQTT), 8883 (MQTT over SSL), 9001 (websockets) and 9883 (websockets over SSL). Certificates have been setup using the Windows CA and converted them to the right format using OpenSSL. I’ve setup your example websockets-3.htm, which runs fine on 9001. But on 9883 I get the message Connection Failed. I also added the option useSSL: true to ensure the client is using SSL. On the Firefox console I see the messages:

    connecting to mqtt-broker.xxxxxxxxx.com 9883 MyMqttScript.js:53:10
    Die Verbindung zu wss://mqtt-broker.xxxxxxxxx.com:9883/mqtt wurde unterbrochen, während die Seite geladen wurde. mqttws31.min.js:36:452
    Die Verbindung zu wss://mqtt-broker.xxxxxxxxx.com:9883/mqtt wurde unterbrochen, während die Seite geladen wurde. mqttws31.min.js:36:422
    Failed MyMqttScript.js:9:10

    On the mosquitto debug output (-v option) I get nothing, when this happens. To check the right SSL setup I also have enabled the http_dir setting in the mosquitto conf and placed a text file in that dir. When accessing any non-existing URL via https://mqtt-broker.xxxxxxxxx.com:9883/blabla I get a 404 back from mosquitto, so SSL looks somehow fine. CA certificate is installed in Firefox to prevent warnings. BUT when trying to access the URL to the existing text file via via https://mqtt-broker.xxxxxxxxx.com:9883/test.txt the connections seems to kept open and I see no response in Firefox. Nothing is shown in the Firefox console and the network analysis window of Firefox shows ne a correct HTTP header, but the content gets not transmitted. In parallel the mosquitto console shows me the message http serving file “”. When accessing the same URL using http://mqtt-broker.xxxxxxxxx.com:9001, the file comes up and mosquitto shows the same message.

    On top I’m not able to activate the logging output of mosquitto to any file. When setting the log_dest to “log_dest file c:\debug.log” mosquitto cancels after about 5s without any message, but the debug.log appears without any content. When changing to “log_dest stdout” without changing anything else, then everything is running. Setting “websockets_log_level 1023” does not bring anything up on stdout.

    It looks to me, that SSL is setup in the right way as the HTTP header is received correctly, but it looks like the content is not transmitted via websockets and the connection is kept open forever (Firefox is still waiting after 30mins and more without coming up with a timeout message). Does someone has any idea what’s wrong with my setup? Or is there any bug in one of the used libs?

    Thanks, Armin

    1. I haven’t tried it on windows for a while. I will install the latest version and give it a try. If you can make the server available over the Internet I will also try to connect just use the ask steve page to send me the details.
      Rgds
      Steve

      1. Hi, I was already able to identify, that this issue is caused by mosquitto itself. The latest working version is 1.6.8. The bug comes up starting with 1.6.9. I already raised an issue in GitHub and they already identified ws lib, which had been changed to a newer version starting from 1.6.9. They already have published a quick fix unter version 1.6.12a.

    2. Hi
      I tried it on Linux and had difficulty like yourself the solution was to add the ca to to certificate list by doing an import.Because you are accessing via mqtt you don’t get a prompt by the browser it just fails.
      If you lace the scripts on the broker and set the http_dir under the ssl listener you should be able to go to the page and get prompted.
      If not you will need to go the manage certificates and do the import.
      Let me know if that solves the problem or not
      Rgds
      Steve

  16. Hi steve..
    I already have mosquitto 1.6.3 installed in ubuntu now i want to have websockets enabled.mosquitto works fine.what are the steps to install and configre websockets?

  17. Hi Steve
    I create ssl certificate on openssl and link this certificate in mosquitto.config file. Whet I test it in my browser then websocket show certificate authority invalid

  18. I have:

    Mosquitto version: 1.5.7
    Rasberry Pi Buster
    Mosquitto as deamon/service.

    See local config below.
    Everything works as expected. But:
    As soon as last part of this config is activated (part with ##)
    Mosquitto is not running at all or very unstable.

    Is it allowed/possible to run 2 instances of websockets??
    To me it seems NOT!

    ====================================================

    # Local config:
    allow_anonymous false
    password_file /etc/mosquitto/passwd

    # start (default) listener on port 1883
    # port 1883 for LAN-only use
    listener 1883
    protocol mqtt

    # start listener on port 8883 with SSL
    # port 8883 is exposed to the internet!
    listener 8883
    protocol mqtt
    certfile /etc/letsencrypt/live/xxx/cert.pem
    cafile /etc/letsencrypt/live/xxx/chain.pem
    keyfile /etc/letsencrypt/live/xxx/privkey.pem

    # start listener on port 9001 for websockets with SSL
    # port 9001 is exposed to the internet!
    listener 9001
    protocol websockets
    http_dir /home/pi/ws9001
    certfile /etc/letsencrypt/live/xxx/cert.pem
    cafile /etc/letsencrypt/live/xxx/chain.pem
    keyfile /etc/letsencrypt/live/xxx/privkey.pem

    ## start listener on port 9002 for websockets no SSL
    ## Second instance van websockets makes Mosquitto instable / unuseable!
    ## start listener on port 9002 for websockets no SSL
    ## port 9002 for LAN-only use
    ## listener 9002
    ## protocol websockets
    ## http_dir /home/pi/ws9002

    1. Hi
      Just tried it on my pi running buster but mosquitto 1.6.8 and seems ok but wasn’t using ssl but two websocket ports open . What symptoms do you get

  19. Hi I’m trying to configurate per listener setting using the configutation
    “””
    per_listener_settings true

    persistence true
    persistence_location /mosquitto/data/
    log_dest file /mosquitto/log/mosquitto.log
    persistence_file mosquitto.db
    log_dest syslog
    log_dest stdout
    log_dest topic
    log_type error
    log_type warning
    log_type notice
    log_type information
    connection_messages true
    sys_interval 5
    log_timestamp true
    persistent_client_expiration 1m
    listener 45000
    protocol websockets
    socket_domain ipv4
    allow_anonymous false
    password_file /mosquitto/config/more/client1.txt
    max_connections 10
    listener 45050
    protocol websockets
    socket_domain ipv4
    allow_anonymous true
    max_connections 10
    “””

    but I got the below error

    “””
    mqtt_1 | 1594127836: mosquitto version 1.6.10 starting
    mqtt_1 | 1594127836: Config loaded from /mosquitto/config/mosquitto.conf.
    mqtt_1 | 1594127836: Opening websockets listen socket on port 45000.
    mqtt_1 | 1594127836: Opening websockets listen socket on port 45050.
    “””

    The configuration without websocket works well.

    Please guide me

  20. Thank you so much.
    I followed the guide and it works.
    I tried to add a for loop with 1000, but all my connection fails after around 29-30
    Do you know how to do load test with it?

  21. Hi Steve,

    georgeous! Thanks a lot, your instructions made a lot clearer to me. Also thanks to your instructions on how to setup CA etc. I love your pages.

    Mosquitto now runs on a Windows machine perfectly secured by SSL/TLS on port 8883.

    I now want to use it via JavaScript and the Websocket solution seems to be right. So I selected port 9002, which is not used anywhere and opened in the firewall (of course).

    I added
    listener 9002
    protocol websockets

    and Mosquitto now starts with this message:

    020-03-02T22:28:53: mosquitto version 1.6.8 starting
    2020-03-02T22:28:53: Config loaded from mosquitto.conf.
    2020-03-02T22:28:53: Opening websockets listen socket on port 9002.
    2020-03-02T22:28:53: libuv support not compiled in
    2020-03-02T22:28:53: Creating Vhost ‘default’ port 9002, 3 protocols, IPv6 off
    2020-03-02T22:28:53: Using SSL mode
    2020-03-02T22:28:53: SSL ECDH curve ‘prime256v1’
    2020-03-02T22:28:53: Opening ipv6 listen socket on port 8883.
    2020-03-02T22:28:53: Opening ipv4 listen socket on port 8883.

    However, I cannot manage to get a connection. On connect I receive error 7, “AMQJS0007E Socket error:undefined.”.
    There are a lot of links regarding that message, mostly linked to version 1.4.x, that the websocket module is not yet included to the Windows Mosquitto version.

    The relevant connection is more of less your code:
    MQTTconnect(); // start MQTT connection

    function MQTTconnect() {
    console.log(‘connecting to ‘ + host + ‘:’ + port);

    mqttClient = new Paho.MQTT.Client(host, port, ‘client_’ + parseInt(Math.random() * 1000, 10));

    var options = {
    timeout: 5,
    useSSL: true,
    onSuccess: onConnect,
    onFailure: onFailure
    };
    mqttClient.onMessageArrived = onMessageArrived;
    mqttClient.onConnectionLost = onConnectionLost;

    mqttClient.connect(options);
    }

      1. Thanks Steve,
        I tried connecting to broker.hivemq.com:8000, but now receive error 1 “AMQJSC0001E Connect timed out.”. Opening via telnet works, so it seem not to be a network issue.

      2. Weird: I also tried test.mosquitto.org:8081. There the connection works!
        This really confuses me. Any idea where to look at?

    1. Steve, thanks again for your time! Really appreciate!

      I found the problem: it was a missing entry of my self signed root certificate. Once I added it, it worked like charm. I’m really happy now!

  22. Hi Steve.
    I am trying a secure connection through websockets and TCP ,using self signed certificates at both client and server side. I am able to connect through TCP using certificates but fail on websockets.
    Although, it works fine without certificates on websockets.
    My mosquitto config file looks like this(running on Ubuntu) :

    port 8885
    log_type error
    log_type notice
    log_type information
    log_type debug
    cafile C:/Program Files/mosquitto/ca.crt
    keyfile C:/Program Files/mosquitto/server.key
    certfile C:/Program Files/mosquitto/server.crt
    require_certificate true
    use_identity_as_username true

    listener 9001
    protocol websockets
    cafile C:/Program Files/mosquitto/ca.crt
    keyfile C:/Program Files/mosquitto/server.key
    certfile C:/Program Files/mosquitto/server.crt
    require_certificate true
    http_dir C:/Program Files/abc

    I am trying to connect through c#(.net) client using MQTTnet dll which is running on Windows machine.
    Below is the c# code of my client :

    options = new ManagedMqttClientOptionsBuilder()
    .WithAutoReconnectDelay(TimeSpan.FromSeconds(30))
    .WithClientOptions(new MqttClientOptionsBuilder()
    .WithClientId(“Vaibhav-PC”)
    .WithWebSocketServer(this.ipTxt.Text)
    .WithTls(new MqttClientOptionsBuilderTlsParameters()
    {
    SslProtocol = System.Security.Authentication.SslProtocols.Default,
    AllowUntrustedCertificates = true,

    UseTls = true,
    Certificates = new List { new X509Certificate2(certificate).Export(X509ContentType.Cert) },
    CertificateValidationCallback = delegate { return true; },
    IgnoreCertificateChainErrors = true,
    IgnoreCertificateRevocationErrors = true
    })
    .WithCleanSession()
    .Build())
    .Build();
    }
    var client = _mqttFactory.CreateManagedMqttClient();
    var message = new MqttApplicationMessageBuilder()
    .WithTopic(this.topicTxt.Text)
    .WithPayload(this.msgTxt.Text + DateTime.Now.ToString())
    .WithExactlyOnceQoS()
    .WithRetainFlag()
    .Build();
    var result = client.StartAsync(options);

    I am able to connect through Paho client on websockets with and without using certificates. But somehow, it fails if i am using .net client.

    1. If it works with the paho Python client then it can’t be a broker issue so it is something in the .net. Unfortunately I’ve never worked with .net so can’t be of much help there.
      Rgds
      Steve

  23. Hi Steve,

    thanks for the tutorial.

    Can I publish a websocket request via http url?

    How would that look like?

    Thanks T

    1. Websockets uses http as part of the initial connection setup and hence it uses the url.
      If you take a look at the Javascript example you will see this

  24. Hi Steve
    i did consider that (for a few seconds) the nodes are at two different locations all doing the same thing. the common point is hiveMq so what you are saying is logical. i had ruled it out because i did not realise that they were unreliable.
    thanks for the reply, it has given me more confidence in my nodes and perhaps less in hiveMq
    Regards
    Dave

  25. hi Steve
    you helped me once before and everything has been working well until recently 🙂
    now however i have run into a problem which is outside my experience.
    using hiveMq with 5 esp nodes connected i suddenly stopped receiving posted messages.
    this can go on for a few days, then just as unexpectedly they start again, sometimes just a few before the next block, then another long wait.
    i have tried changing user id and topics but it has no effect. nodes always connect as does my monitor web page (which also does not receive topics)
    it is almost as though something is filling up and then stopping.
    all messages are quos 0 and none are retained
    is this something you have had experience of in the past
    thank you for your thoughts
    Dave Jelfs

    1. Dave
      Are you sure it isn’t the broker going down?
      The free providers are not very reliable. I’ve experienced many problems with them.
      Rgds
      Steve

  26. Hi Steve,

    I was wondering if you can help me. I have installed Mosquitto successfully in the past but for some reason stuck on a new build. Mosquitto installs correct with both MQTT and Websocket listening on 1883 and 1884 respectively. I can connect to the ports fine, however the publish messages isn’t showing up on Websocket connection. Any ideas?

    Thank you in advance.

    Wally

    1. If you are on windows download the files from the site and use the mosquitto.exe file from the download files as it is an older version that works.
      I had someone the other week with a problem with SSL over websockets and it was because they had a new version of Mosquitto. Sorry but can’t remember which version.

      Note: Problem solved by going back to 1.4.15

  27. Hi Again Steve
    thanks for the quick reply (and link)
    all works fine with hivemq, great stuff
    thanks for your support
    Dave

  28. hi Steve
    thanks for the article, it is most informative
    i am using mqttws31 and trying to connect to test.mosquitto.org with connection string
    ‘ws://test.mosquitto.org:8080/ws’ but get back connection refused
    could you post a link to the html mentioned about please, this might help me to get the connection established
    thanks
    Dave

    1. That broker doesn’t appear to be working over websockets at the moment try this one
      broker.hivemq.com on port 8000.

  29. Hi Steve
    I,m trying to install MQTT in raspberry pi 3 and im getting the below error at the end.
    What the cause?

    Reading package lists… Done
    Building dependency tree
    Reading state information… Done
    Some packages could not be installed. This may mean that you have
    requested an impossible situation or if you are using the unstable
    distribution that some required packages have not yet been created
    or been moved out of Incoming.
    The following information may help to resolve the situation:

    The following packages have unmet dependencies:
    mosquitto : Depends: libssl1.0.0 (>= 1.0.0) but it is not installable
    Depends: libwebsockets3 (>= 1.2) but it is not installable
    N: Ignoring file ‘mosquitto-jessie.list.1’ in directory ‘/etc/apt/sources.list.d/’ as it has an invalid filename extension
    N: Ignoring file ‘mosquitto-jessie.list.2’ in directory ‘/etc/apt/sources.list.d/’ as it has an invalid filename extension
    E: Unable to correct problems, you have held broken packages.

  30. Just a question
    may I manage on a single istance of Mosquitto server both MQTT and WebSoket protocol so connet either a ordinary MQTT client and a browser ?

    is this the corret mosquitto.conf configuration ?

    port 1883
    protocol mqtt
    listener 9001
    protocol websockets

Leave a Reply to Liam Cancel reply

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