使用mqtt.js和Mosca对离线消息造成麻烦

时间:2016-01-21 02:22:54

标签: javascript node.js mqtt

我正在尝试根据mqtt.jsMosca了解如何使用author's demoother instructions发送离线消息。以下是我的尝试,但我不确定为什么我的侦听客户端在线工作,但不是在订阅过程包括离线配置(QoS,clientId,clean)时。

1.使用以下方式启动独立的Mosca经纪人:

npm install mosca bunyan -g
mosca -v | bunyan

2.按顺序运行以下脚本(下面列出):

node subscribe.js   // User8 subscribes to topic called Channel-01 with QoS=1, then closes connection
node send.js        // TxUser sends a message on Channel-01
node listen.js      // User8 reconnects and should see TxUser's message

3.尝试确定listen.js未收到TxUser消息的原因。

以下是我的脚本:

subscribe.js User8使用Channel-01订阅名为QoS=1的主题,然后关闭连接。

var mqtt = require('mqtt');

var client = mqtt.connect({
    servers: [{ host: 'localhost', port: 1883 }]
    , clientId:"User8"
    , clean:false
});

client.subscribe('Channel-01', {qos:1} , function(){
  console.log("Subscriber Client: subscribed and closing connection.");
  client.end();
});

send.js TxUser在Channel-01上发送消息

var mqtt = require('mqtt');

var client = mqtt.connect({
  servers: [{ host: 'localhost', port: 1883 }]
  , clientId:"TxUser"
  , clean:false
});

client.on('connect', function(){
  client.publish('Channel-01', '* * * IMPORTANT msg ' + Date() + ' * * *' , function() {
    client.end( function (){
      console.log('Sender Client: published message and closed connection');
    });
  });
});

listen.js User8重新连接,应该看到TxUser的消息

var mqtt = require('mqtt');

var client = mqtt.connect({
  servers: [{ host: 'localhost', port: 1883 }]
  , clientId:"User8"
  , clean:false
});

client.subscribe('Channel-01');

client.on('message', function(topic, message) {
  // this is never fired when offline options (QoS, clientId, clean) 
  // are configured in subscribe.js 
  console.log('Listener Client: Message Received = ',message.toString());
});

setTimeout(function() {
  console.log('Listener Client: Exiting');
  client.end();
},10*1000);

package.js

{
  "name": "MQTT-Test-System",
  "version": "0.0.1",
  "dependencies": {
    "mosca": "1.0.1",
    "mqtt": "1.6.3"
  }
}

1 个答案:

答案 0 :(得分:1)

好的,我明白这一点。显然,我只需要在{qos:1}脚本中的发布语句中添加send.js。所以看起来应该是这样的:

client.publish('Channel-01', '* * * IMPORTANT msg ' + Date() + ' * * *' , {qos:1}, function() {...etc

为了澄清MQTT.js介绍/演示幻灯片,我向作者提交了PR,更新后的幻灯片为here