toothie
toothie

Reputation: 1029

WebSocket connection establishment error from browser

I have mosquitto MQTT broker running on my machine. And I want to run the MQTT client from browser. This is what I have done in a Django app:

<html>
  <head>
    <title>Mosquitto Websockets</title>
    {% load staticfiles %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="{% static 'js/mqttws31-min.js' %}" type="text/javascript"></script>
    <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script>
    <script src="{% static 'js/config.js' %}" type="text/javasacript"></script>
    <script type="text/javascript">
    var mqtt;
    var reconnectTimeout = 2000;

    function MQTTconnect() {
        host = '127.0.0.1';
        port = 1883;
        useTLS = false;
        cleansession = true;
        username = null;
        password = null;
        mqtt = new Paho.MQTT.Client(host, port,
                    "myclientid_" + parseInt(Math.random() * 100, 10));

        /*mqtt = new Messaging.Client(
                        host,
                        port,
                        "web_" + parseInt(Math.random() * 100,
                        10));
        */
        var options = {
            timeout: 3,
            useSSL: useTLS,
            cleanSession: cleansession,
            onSuccess: onConnect,
            onFailure: function (message) {
                $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
                setTimeout(MQTTconnect, reconnectTimeout);
            }
        };

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

        if (username != null) {
            options.userName = username;
            options.password = password;
        }
        console.log("Host="+ host + ", port=" + port + " TLS = " + useTLS + " username=" + username + " password=" + password);
        mqtt.connect(options);
    }

    function onConnect() {
        $('#status').val('Connected to ' + host + ':' + port);
        // Connection succeeded; subscribe to our topic
        mqtt.subscribe(topic, {qos: 0});
        $('#topic').val(topic);
    }

    function onConnectionLost(response) {
        setTimeout(MQTTconnect, reconnectTimeout);
        $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    };

    function onMessageArrived(message) {

        var topic = message.destinationName;
        var payload = message.payloadString;

        $('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
    };


    $(document).ready(function() {
        MQTTconnect();
    });

    </script>
  </head>
  <body>
    <h1>Mosquitto Websockets</h1>
    <div>
        <div>Subscribed to <input type='text' id='topic' disabled />
        Status: <input type='text' id='status' size="80" disabled /></div>

        <ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
    </div>
  </body>
</html>

I get

WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET   mqttws31-min.js:15
Host=127.0.0.1, port=1883 TLS = false username=null password=null   (index):47

I am new to this so am unable to resolve this. Any help?

Edit1: I tweaked the config file and now it successfully connects to test.mosquitto.org:8080. I subscribed to #, but it is unable to retrieve the published message. I think function onMessageArrived(message) is not working. There are no errors in the console so unable to identify any errors.

enter image description here

Upvotes: 2

Views: 17948

Answers (3)

halbano
halbano

Reputation: 1305

Based on your comment @toothie

"I tried connecting to 'test.mosquitto.org' and got this error: WebSocket connection to 'ws://test.mosquitto.org/:1883/mqtt' failed: Error during WebSocket handshake: Unexpected response code: 404"

The connection string you are sending seems bad formatted. How are you building it?

For me, the separation of concerns using the JSON object definition to instance the library saved me from a couple of headaches:

{
    protocol: 'wss',
    host: `${process.env.MQTT_ENDPOINT}`,
    port: 9001,
    username: 'admin',
    password: '123'
}

Maybe something is helpful for you.

Upvotes: 0

ralight
ralight

Reputation: 11608

Are you sure that you have configured the broker to accept websockets connections on port 1883? By default you would expect this to be listening for MQTT connections, not websockets.

Try putting the following in your config file:

listener 8080
protocol websockets

As Scott says, you could try connecting your client to test.mosquitto.org:8080 to see if it works.

Upvotes: 3

Scott Stensland
Scott Stensland

Reputation: 28285

Here is a site which runs a "MQTT over Websockets" server where the URL can act as a client so you can publish, then have your own browser act as a client subscribing to given topic

http://test.mosquitto.org/ws.html

it might let you tease apart connection issues ... also here is another nodejs library which implements similar functionality

https://www.npmjs.com/package/mqtt-ws

Upvotes: 1

Related Questions