0

I would like to conenct an MQTT broker with Javascript in order to subscript to a topic and publish messages. The connection needs to be done through tcp on port 1883. I am using MQTT.js library. The front end is in angularjs. The example followed is the one in MQTT.js page, though the connection cannot be achieved. Could anyone please help?

Connection through index.html:

<script src="../node_modules/mqtt/browserMqtt.js"></script>

Code for connection:

var client = mqtt.connect('url.com:1883',{clientId :'client1', clean: true});
client.on('connect', function () {
  console.log("onsubscribe");
  client.subscribe('votingSignals', function (err) {
    if (!err) {
      console.log("onsubscribe");
      client.publish('votingSignals', 'start')
    }
 })
})

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

The error displayed is:

WebSocket connection to 'ws://url.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

georgeawg
  • 48,608
  • 13
  • 72
  • 95
MTs
  • 199
  • 2
  • 19

1 Answers1

3

From a web browser you can ONLY use MQTT over Websockets, not native MQTT (over TCP).

This is because the browser will not let you open a normal socket.

hardillb
  • 54,545
  • 11
  • 67
  • 105
  • thank for the answer and edit. Is there a way to connect over TCP (by using proxy maybe)? – MTs Jun 09 '19 at 19:00
  • It is possible to write a proxy, but it's easier to configure the broker to accept MQTT over Websockets – hardillb Jun 09 '19 at 19:18
  • hardillb, one more question, is there a way to combine nodejs (from gulp) and anular js in order to connect the mqtt without websocket? – MTs Jun 09 '19 at 19:57
  • That's far too vague a question, but I'm going to say no – hardillb Jun 10 '19 at 10:35