【问题标题】:Troubles with offline messages using mqtt.js and Mosca使用 mqtt.js 和 Mosca 的离线消息问题
【发布时间】:2016-01-21 02:22:54
【问题描述】:

我正在尝试学习如何使用基于author's demoother instructionsmqtt.jsMosca 发送离线消息。以下是我尝试过的,但我不确定为什么我的监听客户端可以在线工作,但订阅过程包括离线配置(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 使用QoS=1 订阅了一个名为Channel-01 的主题,然后关闭连接。

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"
  }
}

【问题讨论】:

    标签: javascript node.js mqtt


    【解决方案1】:

    好的,我想通了。显然,我只需要在send.js 脚本的发布语句中添加{qos:1}。所以它应该是这样的:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多