Search code examples
javascriptmqttmosquitto

How to connect from MQTT javascript client to Mosquitto Server?


error log in console browser :
"WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET"

my code .js to connect mosquitto server:

var options = {
            clientId: 'web-client',
            connectTimeout: 5000,
            hostname: '127.0.0.1',
            port: 1883,
            path: '/mqtt'
        };

var client = mqtt.connect(options);
  • use library mqtt-2.9.0.js
  • use mosquitto v1.5.4 windows10

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


Solution

  • By default Mosquitto listens on port 1883 and accepts connections using native MQTT

    If you want to connect with MQTT over Websockets you need to configure Mosquitto to listen on a different port and specify to use the websockets transport.

    You can add the following to your mosquitto.conf:

    listener 8883
    protocol websockets
    

    This will cause mosquitto to listen on port 8883 for MQTT over Websockets conections.

    You can then modify your code as follows:

     var options = {
       clientId: 'web-client',
       connectTimeout: 5000,
       hostname: '127.0.0.1',
       port: 8883,
         path: '/mqtt'
       };
    
    var client = mqtt.connect(options);
    

    It's also worth pointing out that your clientId needs to be unique for EVERY client that connects, so you will need to make it dynamic if you are going to load the page more than once at a time.