4
votes

WebSocket Error: Network Error 12031, The connection with the server was reset

I want to subscribe for mqtt message from UI. I am using the following code. I have mosquitto broker running on my machine, so I have given the url as my IP and it is listening on port number 1883, I have given some random Client ID

<!DOCTYPE html>
<html lang="en">

    <head></head>

    <body>
        <script src="../bower_components/jquery/dist/jquery.min.js"></script>
        <script src="../bower_components/jquery/dist/jquery.js"></script>
        <script src="../paho.javascript-1.0.1/mqttws31-min.js"></script>
        <script src="../paho.javascript-1.0.1/mqttws31.js"></script>
        <script src="../js/browserMqtt.js"></script>
        <script>

        // Create a client instance
        client = new Paho.MQTT.Client("10.9.177.110", 1883, "100");

        // set callback handlers
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;

        // connect the client
        client.connect({onSuccess:onConnect});

        // called when the client connects
        function onConnect() {
            console.log("onConnect");
            client.subscribe("/World");
            message = new Paho.MQTT.Message("Hello");
            message.destinationName = "/World";
            client.send(message); 
        }

        // called when the client loses its connection
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:"+responseObject.errorMessage);
            }
        }

        // called when a message arrives
        function onMessageArrived(message) {
            console.log("onMessageArrived:"+message.payloadString);
        }
        </script>
    </body>
</html>
2
If I prefix the host with tcs/ws/https/http it gives the error meassage WebSocket Error: Network Error 12005, The URL is invalidsuma shetty

2 Answers

1
votes

What type of broker are you trying to connect to? Apart from the IBM MessageSight appliance I'm not aware of any other brokers that can share the same port for both native MQTT and MQTT over Websockets.

Since port 1883 is traditionally used for native MQTT have you remembered to add a new listener for MQTT over Websockets?

Assuming you are using mosquitto 1.4.x then you need to add something like this to your config file:

listerner 1884
protocol websockets

This will add a Websocket listener on port 1884

0
votes

Can you confirm that you are running a version of Mosquitto with WebSockets enabled?