我正在尝试使用 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');
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,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/
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您正在使用 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);
...
Run Code Online (Sandbox Code Playgroud)
对于 mqtt 模块,您必须提供 SSL 证书,即使它只是自行生成的证书。
尽管您应该捕获错误...MQTT Broker 日志文件说明了什么?
归档时间: |
|
查看次数: |
3468 次 |
最近记录: |