0
votes

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

1

1 Answers

2
votes

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.