我正在尝试根据mqtt.js和Mosca了解如何使用author's demo和other 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"
}
}