Why is MQTT not connecting with NodeJS?

元气小坏坏 提交于 2020-08-04 18:34:09

问题


I have a weird issue trying to connect to an MQTT server with NODEJS:

If I connect to the MQTT server and I do not get a connect it just hangs.

If I do it with the command line I see data so network, server etc is all good.

If I use a port thats wrong then command line gives me a valid reject message but NODE just hangs.

Command line is:

mosquitto_sub -h 10.10.10.30 -p 1883 -t sim 

My code is completely basic:

var mqtt = require('mqtt');

var MQTT_TOPIC          = "sim";
var MQTT_ADDR           = "10.10.10.30";
var MQTT_PORT           = 1883;
var client = mqtt.connect({host: MQTT_ADDR, port : MQTT_PORT, debug: true});

client.on('connect', function() {
    console.log('Connected');
    client.subscribe(MQTT_TOPIC, function() {
        client.on('message', function(topic, message, packet) {
            console.log(topic + ": '" + message);
        });
    });
});

回答1:


I had the same problem, and figured out a solution. I'm no node.js expert, so it was just a case of trial and error. Maybe somebody else can detail the true problem.

This connection string works for me: var client = mqtt.connect(MQTT_ADDR,{clientId: 'bgtestnodejs', protocolId: 'MQIsdp', protocolVersion: 3, connectTimeout:1000, debug:true});

Full example below:

var mqtt = require('mqtt');

var MQTT_TOPIC          = "hello";
var MQTT_ADDR           = "mqtt://192.168.0.105";
var MQTT_PORT           = 1883;

/* This is not working as expected */
//var client = mqtt.connect({host: MQTT_ADDR, port:MQTT_PORT},{clientId: 'bgtestnodejs'});

/* This works... */
var client  = mqtt.connect(MQTT_ADDR,{clientId: 'bgtestnodejs', protocolId: 'MQIsdp', protocolVersion: 3, connectTimeout:1000, debug:true});

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

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

client.on('error', function(){
    console.log("ERROR")
    client.end()
})

Mosquitto seems to require that the protocolId and protocolVersion is set as above. Additionally, notice that the host and port is not included in the options, but instead given as the first argument.

If I read the documentation correct, the host and port arguments should NOT be given as part of the options, but as a "servers" option, before the options. See this link. I can't get the syntax from that link to work, but the code lines above, seems to the trick.



来源:https://stackoverflow.com/questions/35347724/why-is-mqtt-not-connecting-with-nodejs

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