MQTT的JavaScript客户端未使用WebSockets [英] JavaScript client for MQTT not using WebSockets

查看:93
本文介绍了MQTT的JavaScript客户端未使用WebSockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建AngularJS应用程序,并使用Paho JavaScript客户端通过Web套接字连接到MQTT代理(test.mosquitto.org).这样很好.我想通过直接MQTT连接到MQTT代理(出于完整性的考虑,以支持未启用Websocket的代理).

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).

由于Paho客户端不支持直接MQTT,因此我尝试了mqtt.js(browserMqtt.js)的浏览器版本.

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);

同样,这可以通过WebSockets(端口8080)工作,但是当我尝试通过直接MQTT(端口1883)进行连接时,我在控制台中从browserMqtt.js而不是从我的错误处理程序中获得了错误消息,因为不开火:

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

我的应用程序正在Chrome浏览器上运行.

My app is running on the Chrome browser.

我想知道这是代码问题还是设计问题?是否由于某种原因无法使用MQTT从浏览器连接到代理,并且库正在强制进行WebSocket调用?

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是浏览器支持的协议,而不是普通的TCP套接字(如果要直接运行MQTT,最终将需要它).

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).

浏览器中关于MQTT.js 状态的文档的文档>部分:

The documentation for MQTT.js states in the Browser section:

您的经纪人应接受网络套接字连接

Your broker should accept websocket connection

因此,没有办法可以通过浏览器在WebSocket上使用MQTT.您也许可以创建一个(服务器端)代理,该代理将接受WebSocket连接,以使用简单的MQTT协议将它们传递给目标代理.

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.

这篇关于MQTT的JavaScript客户端未使用WebSockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆