MQTT.js 未从 websockets 连接 [英] MQTT.js not connecting from websockets
问题描述
我正在尝试连接到 MQTT.js 的 websocket 客户端,但无法连接与服务器握手.
I'm trying to connect to websocket client of MQTT.js but unable to get a handshake with the server.
我的代码:
<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>
我收到此错误:WebSocket 连接到ws://broker.hivemq.com:8000/"失败:在收到握手响应之前连接已关闭
.
如果我做错了什么,请告诉我.
Please let me know if I'm doing any mistake.
除了 unpkg.com/mqtt@2.5.0/dist/mqtt.min.js
推荐答案
您的连接选项中缺少 path
.HiveMQ 公共代理在/mqtt 上侦听 websocket 连接,这符合 Eclipse Wiki
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
MQTT 连接上指定的 url 路径部分应为mqtt"例如 ws://m2m.eclipse.org:800/mqtt .mqtt 应该是默认选项,可以配置/指定替代选项
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
您需要在选项中添加 path: '/mqtt'
.
You need to add path: '/mqtt'
in your options.
var options = {
clientId: 'service-3Kx03pKnM2',
connectTimeout: 5000,
hostname: 'xxx.xxx.xxx',
port: 8000,
path: '/mqtt'
};
这篇关于MQTT.js 未从 websockets 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!