Home > Software design >  Switching from mqtts protocol to wss in nodeJS
Switching from mqtts protocol to wss in nodeJS

Time:12-28

I can connect to my MQTT broker, using mqtts protocol like this:

mqtt = require('mqtt')

  let options = {
    host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
    port: 8883,
    path: '/mqtt',
    clientId: 'mqttx_2d803d2743',
    protocol: 'mqtts',
    username: 'light29',
    password: 'Mqtt29@!',
    cleanSession: true,
}

// initialize the MQTT client
let client = mqtt.connect(options);

// setup the callbacks
client.on('connect', function () {
    console.log('Connected');
});

client.on('error', function (error) {
    console.log(error);
});

client.on('message', function (topic, message) {
    // called each time a message is received
    console.log('Received message:', topic, message.toString());
});

// subscribe to topic 'my/test/topic'
client.subscribe('mytest');

// publish message 'Hello' to topic 'my/test/topic'
client.publish('mytest', 'Hello');

This code, yields, as expected:

Connected
Received message: mytest Hello

Now, I would like to connect to this same broker but using wss protocol instead, thus I tried:

 let options = {
    host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
    port: 8884,
    path: '/mqtt',
    clientId: 'mqttx_2d803d2743',
    protocol: 'wss',
    username: 'light29',
    password: 'Mqtt29@!',
    cleanSession: true,
}

However, in this case, I got:

Error: connect ECONNREFUSED 127.0.0.1:8884
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8884
}

CodePudding user response:

I have finally managed to connect with these changes:

let options = {
  
    username: 'light29',
    password: 'Mqtt29@!',

}
// initialize the MQTT client
let client = mqtt.connect('wss://0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud:8884/mqtt', options);

Still, I do not know why explicitly passing protocol, host, port and path does solve it.

CodePudding user response:

The problem in the original is that protocol in the options should be schema and should container URL schema e.g.

let options = {
    host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
    port: 8883,
    path: '/mqtt',
    clientId: 'mqttx_2d803d2743',
    schema: 'mqtts://',
    username: 'light29',
    password: 'Mqtt29@!',
    cleanSession: true,
}

or

let options = {
    host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
    port: 8883,
    path: '/mqtt',
    clientId: 'mqttx_2d803d2743',
    schema: 'wss://',
    username: 'light29',
    password: 'Mqtt29@!',
    cleanSession: true,
}

protocol is not a valid option.

  • Related