Use MQTTNet Server with MQTT.js client

北慕城南 提交于 2019-12-24 09:39:47

问题


I have started an MQTT server just like this example. This code is hosted in an ASP.Net Core 2.0 application but I have tried console application with no luck.

I have also setup a client using the same demo as above and it connects perfectly. Also an Android client connects fine. But I have placed a MQTT.js client webpage but it will not connect with chrome showing net::ERR_CONNECTION_REFUSED error.

I believe that the problem is with server not supporting web sockets. Because if I start my client with WS type it will not connect.

var options = new MqttClientOptions
{
    Server = "localhost",
    //ConnectionType = MqttConnectionType.Tcp // Connects
    ConnectionType = MqttConnectionType.Ws    // Does not connect
};

Now MQTT.js supports TCP as far this link is telling. But I don't seem to be able to work it.

This is the code in my page javascript:

var client = mqtt.connect('tcp://localhost') //Also did mqtt://localhost

client.on('connect', function () {
    client.subscribe('myTopic')
    client.publish('myTopic', 'Hello mqtt')
})

client.on('message', function (topic, message) {
    // message is Buffer
    console.log(message.toString())
    client.end()
})

I want to know how can I make javascript MQTT client to use TCP? (Any other js plugin maybe?) Or alternatively how can I enable WebSockets in MQTTNet. Thanks for your help.


回答1:


MQTT.js does support both native MQTT and MQTT over Websockets, but if you are embedding it in to a web app it can only use MQTT over Websockets because the browsers sandbox will not allow it to use arbitrary TCP connections.

As for enabling Websockets in the broker I can't see anything obvious in the code so you'll probably have to raise and issue against the github project to ask for details.




回答2:


The next version of MQTTnet (2.5) will have support for WebSocket connections for the server via AspNetCore 2.0.



来源:https://stackoverflow.com/questions/46547658/use-mqttnet-server-with-mqtt-js-client

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