简体   繁体   中英

JavaScript client for MQTT not using WebSockets

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.

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.

将连接地址从ws://test.mosquitto.org:1883改为mqtt://test.mosquitto.org:1883

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM