首页 > 解决方案 > NodeJS 使用凭证和 SSL 连接到 MQTT 服务器

问题描述

我正在尝试使用 NodeJS 连接到 MQTT 服务器,但它根本没有连接。这是我正在使用的代码:

const mqtt = require('mqtt');
function Connect(serverName,serverUsername,serverPassword,port,topic,clientName) {
  try{
  //const client = new mqtt.connect('mqtt://'+serverName);
  const client = new mqtt.connect('mqtts://'+serverName,{rejectUnauthorized:false,username:serverUsername,password:serverPassword,connectTimeout:5000});
  console.log('--connecting');
  client.on('connect',function(){
    console.log('--connected');
    client.subscribe(topic,function(err){
      console.log('--subscribed');
      if (!err) {
        client.publish(topic,"hello 2");
      }
    });
  });

  client.on('message',function(tp,msg){
    console.log(msg.toString());
    client.end();
  });

  } catch(e) {
    console.log(e);
  }
}
Connect('mqtt.example.com','myusername','mypassword',9101,'test','NodeApp');

当我运行上面的代码时,console.log里面的所有语句都没有client.subscribe触发。我用这些命令测试了我的 MQTT 服务器,我的所有订阅和发布的消息都可以正常工作:

mosquitto_sub -h mqtt.example.com -p 9101 -t "test" -u "myusername" -P "mypassword" --capath /etc/ssl/certs/

mosquitto_pub -h mqtt.example.com -p 9101 -t "test" -m "This is my message" -u "myusername" -P "mypassword" --capath /etc/ssl/certs/

我究竟做错了什么?

标签: node.jsmqtt

解决方案


您正在使用 mqtts:// 但尚未在连接的选项部分定义您的 SSL 证书:

var caFile = fs.readFileSync("myCAFile");
var certFile = fs.readFileSync("myCertFile");
var keyFile = fs.readFileSync("myKeyFile");

var opts = {
  rejectUnauthorized: false,
  username: serverUsername,
  password: serverPassword,
  connectTimeout: 5000,
  ca: [ caFile ],
  cert: certFile,
  key: keyFile
}

const client = new mqtt.connect('mqtts://'+serverName, opts);
...

对于 mqtt 模块,您必须提供 SSL 证书,即使它只是自行生成的。

虽然您应该发现错误...MQTT Broker 日志文件说明了什么?


推荐阅读