问题
I am building an AngularJS application and using the Paho JavaScript client to connect to an MQTT broker (test.mosquitto.org) via web sockets. This works just fine. I wanted to connect to the MQTT broker via direct MQTT (for sake of completeness to support brokers that do not have websockets enabled).
Since the Paho client does not support direct MQTT, I tried the browserified version of mqtt.js (browserMqtt.js).
Here's the main lines from my code:
//var options = { host: "test.mosquitto.org", port: 8080 }; //works!
var options = { host: "test.mosquitto.org", port: 1883 }; //does not work!
var client = mqtt.connect(options);
Again, this works over WebSockets (port 8080), but when I try to connect over direct MQTT (port 1883), I get the error message message in the console from browserMqtt.js, not from my error handler as that is not firing:
WebSocket connection to 'ws://test.mosquitto.org:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
My app is running on the Chrome browser.
I'm wondering if this a code issue or a design issue? Is it for any reason not possible to connect from a browser to the broker using MQTT and the library is forcing a WebSocket call?
Would appreciate any insights as I'm getting mixed messages from all that I've read over a couple of days but no clear example that I could use as a solution.
回答1:
WebSocket is a protocol that browsers support, as opposed to plain TCP sockets (which you would ultimately require if you want to run MQTT directly).
The documentation for MQTT.js states in the Browser section:
Your broker should accept websocket connection
So there isn't going to be a way around having to use MQTT over WebSocket from browsers. You may be able to create a (server-side) proxy that would accept WebSocket connections to pass them to the target broker using the plain MQTT protocol.
回答2:
Change the connection address from ws://test.mosquitto.org:1883
to mqtt://test.mosquitto.org:1883
来源:https://stackoverflow.com/questions/42746139/javascript-client-for-mqtt-not-using-websockets