1
votes

I'm trying to connect to websocket client of MQTT.js but unable to get a handshake with the server.

My Code :

<html>
<head>
    <title>test Ws mqtt.js</title>
</head>
<body>
    <script src="//unpkg.com/[email protected]/dist/mqtt.min.js"></script>
    <script>
        var options = {
            clientId: 'service-3Kx03pKnM2',
            connectTimeout: 5000,
            hostname: 'xxx.xxx.xxx',
            port: 8000
        };

        var client = mqtt.connect(options);

        client.on('connect', function () {
            client.subscribe('presence');
            client.publish('presence', 'Hello mqtt')
        });

        client.on('message', function (topic, message) {
            console.log(message.toString());
            client.end();
        });
    </script>    
</body>
</html>

I'm getting this error : WebSocket connection to 'ws://broker.hivemq.com:8000/' failed: Connection closed before receiving a handshake response.

Please let me know if I'm doing any mistake.

I'm not using any other scripts other than unpkg.com/[email protected]/dist/mqtt.min.js

1
My vote is for websocket version mismatch of the peers. Please denote the browser info.cagdas
@cagdas: can you please brief it? I couldn't get youRealSteel
Possible handshake issues over websocket are occurring due to the protocol version mismatch between the client and server. So need to check which version of websocket protocol is using on the broker and client like 8 or 13, etc. They may be too old to exchange handshakecagdas
As far as i remember it would be defined on a header or somewhere else. So you may want to check your client library to find it.cagdas
"protocolVersion: 4," from mqtt.js.cagdas

1 Answers

6
votes

You are missing the path in your connection options. The HiveMQ public broker listens on /mqtt for websocket connections, which is in accordance with the Eclipse Wiki

The path portion of the url specified on the MQTT connect should be "mqtt" For instance ws://m2m.eclipse.org:800/mqtt . mqtt should be the default with the option for an alternative to be configured / specified

You need to add path: '/mqtt' in your options.

var options = {
        clientId: 'service-3Kx03pKnM2',
        connectTimeout: 5000,
        hostname: 'xxx.xxx.xxx',
        port: 8000,
        path: '/mqtt'
    };