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 on 8884

Here is a list of other test brokers with Port numbers

Serving Web Pages On Mosquitto

When websockets are enabled on mosquitto you have the option of serving standard html web pages.

I use this to serve the Javascript MQTT page.

You need to create a folder to store your web pages e.g web and then add the following entry into the conf file

http_dir path to folder/web

Notice there is no trailing slash.

to connect to the page use:

http://broker:9001/webpage.html

Again notice that the port is the port you are using for websockets.

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.

MQTT explorer supports websockets and SSL

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

133 comments

  1. hi steve can you help me with this
    i got mosquitto.conf file

    persistence true
    persistence_location /var/lib/mosquitto/

    #log config
    log_dest file /var/log/mosquitto/mosquitto.log
    log_timestamp true
    log_type all

    listener 1883
    protocol mqtt

    listener 1884
    protocol websockets
    socket_domain ipv4

    allow_anonymous true
    include_dir /etc/mosquitto/conf.d

    and i tried to start mosquitto service but it just cant. I dont know what is the problem. Can you help me

    1. What error message do you get? Are you sure it isn’t already running as the install starts its as a service by default.
      Rgds
      Steve

      1. i kinda sure that the service ist running bofere that cus i have restart the service and check for the service status and it isnt running. I checked for the log file but its didnt log anything and i didnt get any message too.

        1. Hi
          Stop the service
          sudo service mosquitto stop
          and start it from the command line
          mosquitto -v
          and see if it starts ok
          rgds
          steve

  2. hey steve
    this is my conf for the mqtt broker
    # 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

    per_listener_settings true

    pid_file /var/run/mosquitto.pid

    persistence true
    persistence_location /var/lib/mosquitto/

    log_dest file /var/log/mosquitto/mosquitto.log
    #log_type all

    include_dir /etc/mosquitto/conf.d
    #listener 1883
    #allow_anonymous false

    #password_file /etc/mosquitto/passwordfile
    # MQTT Listener Configuration

    listener 8083
    protocol websockets

    #allow_anonymous false

    #password_file /etc/mosquitto/passwordfile
    #acl_file /etc/mosquitto/acl.file
    cafile /etc/mosquitto/certs/ca.crt
    keyfile /etc/mosquitto/certs/server-nopass.key
    certfile /etc/mosquitto/certs/server.crt

    require_certificate false
    #tls_version tlsv1.2

    listener 8883
    protocol mqtt
    allow_anonymous false

    # Uncomment and configure password_file if using username/password authentication
    password_file /etc/mosquitto/passwordfile
    acl_file /etc/mosquitto/acl.file

    cafile /etc/mosquitto/certs/ca.crt
    keyfile /etc/mosquitto/certs/server-nopass.key
    certfile /etc/mosquitto/certs/server.crt

    require_certificate false

    tls_version tlsv1.2

    and I want to connect it as per your ssl webpage but it does not connect and logs this message on the console
    mqttws31.js:979 WebSocket connection to ‘wss://192.168.200.167:8083/mqtt’ failed:
    this is the code for the webpage

    JavaScript MQTT WebSocket Example

    var mqtt;
    var reconnectTimeout = 2000;
    var host=”192.168.200.167″; //change this
    //var host=”IOT”; //change this
    //var host=”m21.cloudmqtt.com”;
    //var host=”test.mosquitto.org”; //change this
    //var host=”iot.eclipse.org”;
    //var port=9001;
    var port =8083;
    //r port=37363;
    //var port=443;

    function onConnect() {
    // 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 = {
    useSSL:true,
    timeout: 3,

    // userName:”systellex1″,
    // password:”systellex123”,
    mqttVersion:4,
    onSuccess: onConnect

    };

    mqtt.connect(options); //connect
    }

    Main Body

    MQTTconnect();

    1. You need allow anonymous true and remove the line mqttVersion:4,

      In the browser enable web console and see what error messages you get and also on the broker see what messages are displayed.
      Rgds
      Steve

  3. Hi Steve,

    Thanks for giving HiveMQ a mention in this article. Under the section ‘Using an External MQTT Broker with Websockets, ‘ you have stated as below:

    “broker.hivemq.com -uses port 8000 for websockets. Websockets over SSL not supported.”

    Kindly update this information because ‘broker.hivemq.com’ (https://www.mqtt-dashboard.com/) supports SSL. Here’s the updated info:

    TCP Port: 1883
    Websocket Port: 8000
    TLS TCP Port: 8883
    TLS Websocket Port: 8884

    Thank you in advance for making this update. I look forward to seeing the updated article soon.

  4. Hi!
    I’m trying to connect to an external MQTT broker over websockets in Python, and I allways get the error:
    “socket.gaierror: [Errno 11001] getaddrinfo failed”
    I can connect perfectly to the broker through “MQTT Explorer”, indicating the same parameters [host, port, username, password, protocol=”ws://”, and Server certificate (CA)] and checking the options “Validate certificate”=true and “Encryption (tls)” = true.
    I live the piece of the Python code, just in case:
    clientMQTT = paho.mqtt.client.Client(transport=’websockets’) # paho.mqtt.client.Client(client_id=’PUBLISHER_2′, transport=’websockets’, clean_session=False)
    clientMQTT.on_connect = on_connect
    clientMQTT.on_disconnect = on_disconnect
    myHost = ‘smart.iot.gijon.es/mosquitto-pre/ws’ #’wss://smart.iot.gijon.es/mosquitto-pre’
    myPort = 443
    myUser =
    myPassword =
    myCertificate = ‘.\certificate.ca.crt’
    clientMQTT.username_pw_set(myUser, myPassword)
    clientMQTT.tls_set(ca_certs=myCertificate)
    clientMQTT.connect(host=myHost, port=myPort)

    I tried adding next two code lines, but I get the same result:
    clientMQTT.tls_set(ca_certs=myCertificate, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2)
    clientMQTT.tls_insecure_set(False)

    I really appreciate if someone could help me. Thanks.

    1. The error looks like a DNS lookup error. Is your broker accessible over the Internet if so I can try it using my python client?
      Rgds
      Steve

      1. Hi Steve!
        Thank you so much for your help.
        The url of the broker where I have to connect is “wss://smart.iot.gijon.es/mosquitto-pre” and port 443.
        I do ping to ‘smart.iot.gijon.es’ perfectly, but not to ‘smart.iot.gijon.es/mosquitto-pre’.
        I have verify that assigning host parameter to “smart.iot.gijon.es/mosquitto-pre”, “smart.iot.gijon.es/mosquitto-pre/ws” or “wss://smart.iot.gijon.es/mosquitto-pre” I get the error:
        “socket.gaierror: [Errno 11001] getaddrinfo failed”
        However, if I only put “smart.iot.gijon.es” as host, the process seems to reach the host and it is the SSL verification that fails:
        “ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for ‘smart.iot.gijon.es’. (_ssl.c:1129)”

        ¿What is the problem with the suffix “/mosquitto-pre”? I have been given the url to connect containing that suffix. It is supposed that it has to work.

  5. Hi Steve!
    I’ve created my CA certs following your tutorial. But when I use websocket over TLS (add listener 8081), It’s not worked. I’ve checked my port by netstat and don’t see my port [::]:8081. Evenwhen using listener 9001 it’s not worked too!
    After that i’m compiling by command:

    mosquitto -c mosquitto.conf -v

    then got errors: Error: Unable to create websockets listener on port 8081.

    C:\mosquitto>mosquitto -c mosquitto.conf -v
    1675845322: mosquitto version 2.0.15 starting
    1675845322: Config loaded from mosquitto.conf.
    1675845322: Opening websockets listen socket on port 8081.
    1675845322: Error: Unable to create websockets listener on port 8081.

    Please help me to solve that problem. Thank you!

    1. It looks like mosquitto is already running
      use
      sudo service mosquitto stop

      to stop the running version and try again
      rgds
      steve

      1. Yes, I’ve restarted mosquitto many times, but it still has that problem 🙁
        I searched on Google, and they suggest fixing something in the libwebsockets library. It is not worked (for me)

        https://github.com/eclipse/mosquitto/issues/1924
        https://github.com/openwrt/packages/commit/689dabd8de667344b89e09e858d73204423640a9#diff-5c6807a621ca261b98af0eb119c5c9866610a7fb049fe38ec0b3ba0542e33232

        I tried to use my friend’s laptop (window 11) and got the same issue.

        1. Hi
          You are trying to start mosquitto manually from the command line but it may already be running as it is started as a service. Use netstat to see what ports are open. Are you on LInux or windows
          Rgds
          Steve

          1. Hi Steve
            Thank you for your answer.
            I am using windows 11. I’ve uninstalled mosquitto version 2.0.15 and installed mosquitto 2.0.11.
            And now it’s working normally. Maybe the newest version is not supported or something else.
            Hien

  6. Hi again.
    Just forget my previous request. I got it working by using websocket-stream.

    MyBroker now looks like this:

    import * as aedes from ‘aedes’
    import * as ws from ‘websocket-stream’
    import * as http from ‘http’

    export class MyBroker {
    aedes: aedes.Aedes
    httpServer: http.Server
    port: number

    constructor(port: number) {
    this.port = port
    this.aedes = aedes.Server()
    this.httpServer = http.createServer()

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    ws.createServer({ server: this.httpServer }, this.aedes.handle)

    this.httpServer.listen(this.port, () => {
    console.log(‘Broker is listening on port ‘/*, this.httpServer*/)
    })
    }

  7. Hi Steve!

    Great article. Thanks!

    I’m trying to get MQTT to work on my machine, but I need help. I can’t connect to my own broker (aedes.js in node.js). Connection to a 3rd party broker works just fine. Perhaps you could give me some hints on what I’m doing wrong.

    I’m using mqtt.js in frontend (running in a browser), like this:

    return mqtt.connect(‘ws://localhost:1883’) // Gives a ‘WebSocket connection to ‘ws://localhost:1883/’ failed’
    // return mqtt.connect(‘ws://test.mosquitto.org:8080’) // This works!

    I’m using aedes.js in my backend (running via node.js), like this:

    const myBroker = new MyBroker(1883)

    MyBroker lokes likes this:

    import * as aedes from ‘aedes’
    import * as net from ‘net’

    export class MyBroker {
    aedes: aedes.Aedes
    broker: net.Server
    port: number

    constructor(port: number) {
    this.aedes = aedes.Server()
    this.broker = net.createServer(this.aedes.handle)
    this.port = port
    this.broker.listen(this.port, () => {
    console.log(‘Broker is listening on port ‘, this.broker)
    })
    }

    If I start a client in my backend (in node.js) connection works fine and I can subscribe and publish messages. But starting a client in my frontend won’t connect (even if I use my IP instead of localhost). Everything (backed/frontend) runs on my computer. The problem must be network related somehow.

    Any help would be very appreciated!

    1. It is probably because websockets isn’t enabled on the broker. I don’t know the exact setting as I have only done it through node-red.
      Rgds
      Steve

  8. Hi Steve,
    I am trying to connect to mosquitto broker from an Angular application using ‘wss’ protocol.
    However I am not able to succeed in it. I have tried almost all the possible permutations and combinations.
    Created client and server certificates as per your tutorial..
    When I see the mosquitto broker logs it displays following error – SSL_ERROR_WANT_READ
    ——————————————————————-
    Detailed logs:
    1657782067: lws_close_free_wsi: shutting down connection: 0x1cc4920
    1657782067: lws_close_free_wsi: real just_kill_connection: 0x1cc4920
    1657782067: remove_wsi_socket_from_fds: wsi=0x1cc4920, sock=19, fds pos=2, end guy pos=3, endfd=20
    1657782072: Accepted 0x1cc4920 to tsi 0
    1657782072: inserted SSL accept into fds, trying SSL_accept
    1657782072: SSL_ERROR_WANT_READ
    1657782072: SSL_ERROR_WANT_READ
    1657782072: lws_close_free_wsi: shutting down connection: 0x1cc4920
    1657782072: lws_close_free_wsi: real just_kill_connection: 0x1cc4920
    1657782072: remove_wsi_socket_from_fds: wsi=0x1cc4920, sock=19, fds pos=2, end guy pos=3, endfd=20
    1657782072: Accepted 0x1cc4920 to tsi 0
    1657782072: inserted SSL accept into fds, trying SSL_accept
    1657782072: SSL_ERROR_WANT_READ
    1657782072: lws_close_free_wsi: shutting down connection: 0x1cc4920
    1657782072: lws_close_free_wsi: real just_kill_connection: 0x1cc4920
    1657782072: remove_wsi_socket_from_fds: wsi=0x1cc4920, sock=19, fds pos=2, end guy pos=3, endfd=20
    1657782075: Received PINGREQ from Telegraf-Consumer-XSjhk
    1657782075: Sending PINGRESP to Telegraf-Consumer-XSjhk
    1657782075: Received PINGREQ from mqtt767436659828126
    1657782075: Sending PINGRESP to mqtt767436659828126
    1657782077: Accepted 0x1cc4920 to tsi 0
    1657782077: inserted SSL accept into fds, trying SSL_accept
    1657782077: SSL_ERROR_WANT_READ
    1657782077: lws_close_free_wsi: shutting down connection: 0x1cc4920
    1657782078: lws_close_free_wsi: real just_kill_connection: 0x1cc4920
    1657782078: remove_wsi_socket_from_fds: wsi=0x1cc4920, sock=19, fds pos=2, end guy pos=3, endfd=20
    1657782080: Accepted 0x1cc4920 to tsi 0
    ———————————————————————————————
    Mosquitto config:
    # 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
    #capath

    listener 1883

    listener 8883
    protocol websockets
    cafile /etc/mosquitto/ca_certificates/ca.crt
    keyfile /etc/mosquitto/certs/server-nopass.key
    certfile /etc/mosquitto/certs/server.crt
    #require_certificate false

    connection_messages true
    log_timestamp true
    log_type websockets
    log_type error
    log_type warning
    log_type notice
    log_type information
    log_type debug
    log_type subscribe
    log_type unsubscribe
    log_type all
    websockets_log_level 14

    pid_file /var/run/mosquitto.pid

    persistence true
    persistence_location /var/lib/mosquitto/

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

    include_dir /etc/mosquitto/conf.d

    tls_version tlsv1.2
    ———————————————————————-
    Angular app using ngx mqtt config:
    export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {

    hostname: env.mqtt.server,

    port: env.mqtt.port,

    protocol: (env.mqtt.protocol === “wss”) ? “wss” : “ws”,

    path: ”,

    cert: AppConstant.assets + ‘client.crt’,

    ca:AppConstant.assets + ‘ca.crt’,

    key:AppConstant.assets + ‘client.key’,

    }

    Note: I tried with both client and server certs in my angular application.

    Any suggestion would be helpful !!

    1. Hi
      I seem to remember I had a similar problem with my Javascript client but didn’t resolve it. I will take another look.
      Are you using your own ca?
      Have you tried my JavaScript client?
      How are you with python as I have a python test script that may be helpful.
      Rgds
      Steve

    2. Ok
      I just checked it and what I needed to do is open the page in a browser. The page doesn’t exist but you get the safety warning and you can add it as an exception
      my server is mint2.home
      I went to https://mint2.home:9002
      went through the warnings and added the site and then MY Javascript client worked on both firefox and chrome
      rgds
      steve

  9. Hi Steve,
    i’am tring to install MQTT broker in windows server 2019. So i got a problem.
    this is my configure file:
    listener 1883
    listener 9001
    protocol websockets.

    when i use the version 2.0.14. The 9001 only listen on IPV6.
    so i go back to 2.0.9a. The 9001 only listen on IPV4.

    netstat like this:
    C:\Users\Administrator>netstat -ano|findstr “9001”
    TCP 0.0.0.0:9001 0.0.0.0:0 LISTENING 11344

    but for 1883, it can listen both IPV4 and IPV6.
    C:\Users\Administrator>netstat -ano|findstr “1883”
    TCP 0.0.0.0:1883 0.0.0.0:0 LISTENING 6116
    TCP [::]:1883 [::]:0 LISTENING 6116

    anyway, now i can use it,^_^.

  10. Hi Steve,

    I am currently using a broker having a username and a password. What changes should I do in order to have access to the broker through JavaScript code? I have tried adding two key-value fields as : username:”username”, password:”password” but no access was granted.

    Thanks

    1. hi
      I’ve copied the cnnection code form a working script which users variables for the username/password just replace them with the actual values
      var options = {
      timeout: 6,
      cleanSession: clean_sessions,
      onSuccess: onConnect,
      onFailure: onFailure,

      };
      //console.log(“connecting with username “+user_name);

      options.userName=user_name;
      options.password=password;

      mqtt.onConnectionLost = onConnectionLost;
      mqtt.onMessageArrived = onMessageArrived;
      mqtt.onConnected = onConnected;

      mqtt.connect(options);

  11. Hi Steve, I’m testing MQTT in a Vue.js app using MQTTJS (https://github.com/mqttjs/MQTT.js). I am unable to connect to the (Mosquitto) broker using mqtt protocol but it works fine with websockets.

    If I’m reading your article correctly this is a limitation of running in a browser and there’s no way round it. Is that correct?

    Thanks.

    1. Hi
      That is correct. The browser doesn’t currently support MQTT. They are dropping support for FTP and so maybe they will add MQTT.

  12. Hi Steve, any idea why a site hosted using HTTPS wouldn’t be able to connect to Mosquitto MQTT port 8080/8081? It seems like the Websocket endpoint on Mosquitto is insecure (uses only WS) and the HTTPS site needs to use WSS.

  13. Dear Steve,
    I have an under the hood question re MQTT Websockets:

    Is it correct to assume that an MQTT Websockets client connected to the Broker uses a single connection (open socket) regardless of the number of subscriptions it is subscribed to?

    if so, performance-wise, it doesn’t matter if the client has 3 or 10 active subscriptions?
    Many thanks in advance!
    Best,
    Ram

    1. Correct. A MQTT + websockets connection is the same as a normal MQTT connection except that it has the websockets outer envelope.
      So what works for MQTT works for MQTT over websockets.
      Rgds
      Steve

  14. Hello,
    I’m trying to connect to my MQTT broker which is running on RPI4 but every thing I tried doesn’t work.
    WebSocket connection to ‘ws://myRaspberyPiIP:9002/mqtt’ failed:

    This is my javasrpit code:
    let client
    client = new Paho.MQTT.Client(“myRaspberyPiIP”, 9002,”CLientID123456″);

    function povezano()
    {
    console.log(“Connectin successful”);
    }

    function napaka()
    {
    console.log(“Fail”);
    }

    let options = {
    timeout: 5,
    onSuccess: povezano,
    onFailure: napaka,
    };

    client.connect(options);

    I am sure that broker is configured OK,
    listener: 9002 as it said in this tutorial,
    anonymous: true
    protocol: websocket

    what am I doing wrong?

    thanks for answers in advance

  15. 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

  16. 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

  17. 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

  18. 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 ?!

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

  20. 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

  21. 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…

  22. 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.

  23. 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.

  24. 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.

  25. 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.

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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?

  31. 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

  32. 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

  33. 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

  34. 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?

  35. 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!

  36. 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

  37. 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

  38. 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

  39. 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

  40. 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

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

  42. 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.

  43. 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.

  44. 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

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