Search code examples
javascriptwebsocketmqttmosquitto

MQTT mosquitto - Implementing websocket in javascript using mqttws31.js


Implementing a websocket using MQTT with mosquitto broker using javascript by including mqttws32.js file.

Mosquitto version: 1.4.9

On start I got:

rohan@rohan-PC:~$ mosquitto
1470241326: mosquitto version 1.4.9 (build date Fri, 03 Jun 2016 09:22:47 +0100) starting
1470241326: Using default config.
1470241326: Opening ipv4 listen socket on port 1883.
1470241326: Opening ipv6 listen socket on port 1883.

As latest version of mosquitto supports Web socket.

I'm using following code:

client = new Paho.MQTT.Client("localhost", 1883, "myclientid_" + parseInt(Math.random() * 100, 10));

Getting error:

WebSocket connection to 'ws://localhost:1883/mqtt' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

I listener i got:

1470241581: New connection from ::1 on port 1883.
1470241581: Socket error on client <unknown>, disconnecting.

After searching I found a solution to add following line to mosquitto.conf file

listener 1884
protocol websockets

I changed to port to 1884 but still getting the same error.


Solution

  • Mosquitto does not have a default config file location so you need to actually specify it on the command line

    $ mosquitto -c /path/to/mosquitto.conf
    

    The config file also should have an extra line in it if you still want to listen on 1883 for native MQTT connections as well as websockets on 1884

    port 1883
    
    listener 1884
    protocol websockets
    

    That should get you a functioning broker that is actually listening for MQTT over Websockets on port 1884