如何通过WebSocket连接MQTT Broker?连接失败求助
Hey there, let’s work through this issue step by step. The error you’re seeing ("Connection closed before receiving a handshake response") usually points to one of a few common problems—here are the most likely fixes:
1. Switch to Secure WebSocket (WSS) Instead of WS
Modern browsers restrict unencrypted WebSocket (ws://) connections when you open a local HTML file directly via the file:// protocol (this is a security measure to prevent unsecure traffic from local files).
Try updating your connection URL to use the secure WebSocket endpoint for HiveMQ’s public broker:
var client = mqtt.connect('wss://broker.hivemq.com:8001')
This should bypass the browser’s security restrictions for local files and let you connect successfully.
2. Serve Your HTML File via a Local HTTP Server
If you still want to use ws://, you need to access your test.html file through a local web server instead of opening it directly. This removes the file:// origin restriction that’s blocking the connection.
Using Python: If you have Python installed, open a terminal in the folder with
test.htmland run:# For Python 3 python -m http.server 8000 # For Python 2 python -m SimpleHTTPServer 8000Then open Chrome and navigate to
http://localhost:8000/test.html.Using Node.js: Install
http-servervia npm first:npm install -g http-serverThen run:
http-serverAccess your file at the URL provided (usually
http://localhost:8080/test.html).
3. Verify the Broker Endpoint is Reachable
Occasionally, public MQTT brokers might experience downtime or have endpoint changes. You can test if HiveMQ’s broker is up using a tool like MQTT Explorer:
- Try connecting to
ws://broker.hivemq.com:8000orwss://broker.hivemq.com:8001to confirm the broker is accepting connections.
Modified Working Code Example
Here’s your code updated with the WSS endpoint, which should work when opening the file directly in Chrome:
<html> <head> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> </head> <body> <script> var client = mqtt.connect('wss://broker.hivemq.com:8001') client.subscribe("mqtt/demo") client.on("message", function (topic, payload) { alert([topic, payload].join(": ")) client.end() }) client.publish("mqtt/demo", "hello world!") </script> </body> </html>
Give these steps a try—most likely switching to WSS or serving via a local server will resolve your issue.
内容的提问来源于stack exchange,提问作者nowox




