0

1/产生错误:

-文件经纪人.js:

const fs = require('fs')
const aedes = require('aedes')()
const port = 8883    
const options = {
  key: fs.readFileSync('cert/key.pem'),
  cert: fs.readFileSync('cert/crt.pem')
}    
const server = require('tls').createServer(options, aedes.handle)    
server.listen(port, function () {
  console.log('MQTT broker server started and listening on port ', port)
})

-文件 sub.js :

var mqtt    = require('mqtt');
const fs = require('fs');
var caFile = fs.readFileSync("cert/ca.ca");
//if using client certificates
var KEY = fs.readFileSync('cert/key.pem');
var CERT = fs.readFileSync('cert/crt.pem');
var options={
  clientId:"mqttjs01",
  //port:8883,
  //host:'192.168.1.71',
  //protocol:'mqtts',
  rejectUnauthorized : false,
  ca:caFile,
  key: KEY,
  cert: CERT
}
var client  = mqtt.connect("mqtts://domain.com:8883",options);    
//console.log("connected flag  " + client.connected);    
client.on('connect', function () {
  console.log('Connected');
  client.subscribe('message')
})
client.on('message', function (topic, message) {
    context = message.toString();
    console.log("sub:",topic+'-'+context)
})

-文件 pub.js :

var mqtt    = require('mqtt');
const fs = require('fs');
var caFile = fs.readFileSync("cert/ca.ca");
//if using client certificates
var KEY = fs.readFileSync('cert/key.pem');
var CERT = fs.readFileSync('cert/crt.pem');
var options={
  clientId:"mqttjs01",
  //port:8883,
  //host:'192.168.1.71',
  //protocol:'mqtts',
  rejectUnauthorized : false,
  ca:caFile,
  key: KEY,
  cert: CERT
}
var client  = mqtt.connect("mqtts://domain.com:8883",options);

//console.log("connected flag  " + client.connected);
var dem =0;
client.on('connect', function () {
    console.log('Connected');    
    setInterval(function() {
        client.publish('message', 'Hello mqtt ' + dem);
        console.log('Message Sent ' + dem);
        dem = dem + 1;
    }, 5000);
});

2/ 错误状态:

  • 文件 broker.js:运行正常"MQTT broker server started and listening on port 8883"
  • 文件 sub.js:显示"Connected"但没有值显示。-> 预计"Message Sent ..."每 5 秒显示一次。
  • 文件pub.js:每隔乱秒显示"Connected"显示。"Message Sent ..."

过去,我用 mosca 设置完成,但是当更改为 aedes 时,它没有运行,我做错了什么吗?

4

1 回答 1

0

在@hardillb 的帮助下,我已经修复了它。因此更改 sub 和 pub 中的 clientId,而不是删除它并且值可以传递。

于 2021-05-17T14:25:14.880 回答