MQTT Node.js模块的Mosquitto持久性问题

时间:2018-10-26 09:42:26

标签: mqtt mosquitto

我正在尝试使用mosquitto代理运行基本队列实现,当使用者和生产者正常运行时,它可以正常工作。如果我运行生产者,然后运行消费者,则无法获取消息(数据)。在将消息发布到主题时,我正在使用qos:2。我在mqtt.js中使用nodejs语言

consumer.js

const mqtt = require ('mqtt');
var options = {}
options.clientId = 'mqttjs_consumer'
options.clean = false
options.debug = true
var client  = mqtt.connect('mqtt://localhost',options);

client.on('connect', function () {
  client.subscribe('topic/sample',function(){
    console.log('client has subscribed successfully');
  });

});

client.on('message', function (topic, message){
  console.log(message.toString());
});

Producer.js

const mqtt = require ('mqtt');
var options = {}
options.clientId = 'mqttjs_producer'
options.debug = true
var client  = mqtt.connect('mqtt://localhost',options);

client.on('connect', function(){
  client.publish('topic/sample','message_data',{qos:2},function(err,status){
    console.log(err,status)
    process.exit(0)
  })
});

1 个答案:

答案 0 :(得分:0)

您需要在QOS 2上订阅,而不仅仅是在QOS 2上发布。

const mqtt = require ('mqtt');
var options = {}
options.clientId = 'mqttjs_consumer'
options.clean = false
options.debug = true
var client  = mqtt.connect('mqtt://localhost',options);

client.on('connect', function () {
  client.subscribe('topic/sample',{qos:2}, function(){
    console.log('client has subscribed successfully');
  });

});

client.on('message', function (topic, message){
  console.log(message.toString());
});