MQTT.js 未从 websockets 连接

Rea*_*eel 1 websocket mqtt

我正在尝试连接到MQTT.js 的websocket 客户端,但无法与服务器握手。

我的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

我收到此错误:WebSocket connection to 'ws://broker.hivemq.com:8000/' failed: Connection closed before receiving a handshake response

如果我做错了什么,请告诉我。

我没有使用任何其他脚本 unpkg.com/mqtt@2.5.0/dist/mqtt.min.js

fra*_*hbi 6

path的连接选项中缺少。HiveMQ 公共代理在 /mqtt 上侦听 websocket 连接,这与Eclipse Wiki 一致

MQTT 连接上指定的 url 路径部分应为“mqtt”,例如 ws://m2m.eclipse.org:800/mqtt 。mqtt 应该是默认选项,可以配置/指定替代选项

您需要添加path: '/mqtt'您的选项。

var options = {
        clientId: 'service-3Kx03pKnM2',
        connectTimeout: 5000,
        hostname: 'xxx.xxx.xxx',
        port: 8000,
        path: '/mqtt'
    };
Run Code Online (Sandbox Code Playgroud)