JavaScript client for MQTT not using WebSockets

风流意气都作罢 提交于 2021-01-27 06:55:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!