问题
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