MQTT.js not connecting from websockets

自古美人都是妖i 提交于 2021-02-10 16:21:46

问题


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/mqtt@2.5.0/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/mqtt@2.5.0/dist/mqtt.min.js


回答1:


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'
    };


来源:https://stackoverflow.com/questions/43000448/mqtt-js-not-connecting-from-websockets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!