我正在尝试学习如何使用 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的消息。
这是我的脚本:
订阅.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"
}
}
最佳答案
好吧,我明白了。显然,我只需要在 send.js
脚本的发布语句中添加 {qos:1}
即可。所以它应该看起来像:
client.publish('Channel-01', '* * * IMPORTANT msg ' + Date() + ' * * *' , {qos:1}, function() {...etc
关于javascript - 使用 mqtt.js 和 Mosca 的离线消息问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914317/