使用TLS的node.js mqtt客户端 [英] node.js mqtt client using TLS
问题描述
我正在尝试使用以下程序包使用TLS实现node.js mqtt客户端;
I am trying to implement a node.js mqtt client with TLS using the package below;
https://www.npmjs.com/package/mqtt#client
在不使用TLS的情况下运行mqtt客户端的代码如下;
The code for running mqtt client without TLS is as follows;
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
如何修改以上代码以在mqtt客户端上使用TLS?
How should the above code be modified to use TLS on the mqtt client?
使用以下命令以独立方式运行mosca MQTT代理;
The mosca MQTT broker was run as a stand-alone using the command below;
mosca --key ./tls-key.pem --cert ./tls-cert.pem --http-port 3000 --http-bundle --http-static ./ | pino
推荐答案
足以将URL的protocol
部分更改为mqtts://
Should be enough to change the protocol
part of the URL to mqtts://
mqtts://test.mosquitto.org
.
自签名证书
使用自签名证书(仅用于测试目的)时,可以将以下选项传递给connect
函数:
You can pass the following option to the connect
function when using self-signed certificates (for testing purposes only):
mqtt.connect('mqtts://test.mosquitto.org', {
rejectUnauthorized: false
});
这篇关于使用TLS的node.js mqtt客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!