【发布时间】:2016-01-21 02:22:54
【问题描述】:
我正在尝试学习如何使用基于author's demo 和other instructions 的mqtt.js 和Mosca 发送离线消息。以下是我尝试过的,但我不确定为什么我的监听客户端可以在线工作,但订阅过程包括离线配置(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