node.js - 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/
我究竟做错了什么?
解决方案
您正在使用 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 日志文件说明了什么?
推荐阅读
- pagination - 用 Blazor 中加载的图像填充 div
- java - 如何使用执行器服务从多个文件中执行添加并给出最终输出
- regex - 添加关于在 VScode 中自动关闭 SASS/CSS 括号的注释
- python - 如果不存在,则使用 Python 和 SQL 插入记录
- r - 使用函数在循环中创建多个子集
- ruby-on-rails - 在 Rails 上创建创建或更新路由的正确方法是什么
- git-bash - chmod 命令在 GitBash 中的 Windows 上不起作用吗?
- javascript - 通过浏览器更改背景颜色以匹配视频更改
- r - 如何将此数据框(超过 2 行)转换为 R 中的事务?
- java - JMeter 从 SFTP 文件夹中获取最新的文件/内容