The question is published on by Tutorial Guruji team.
I’m trying to learn how to send offline messages using mqtt.js and Mosca based on the author’s demo and other instructions. Below is what I attempted, but I’m not sure why my listening client works online, but not when the subscription process includes offline configuration (QoS, clientId, clean).
1.Start a standalone Mosca broker using:
npm install mosca bunyan -g mosca -v | bunyan
2.Run the following scripts (listed below) sequentially:
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.Attempt to identify why listen.js
does not receive TxUser’s message.
Here are my scripts:
subscribe.js
User8 subscribes to a topic called Channel-01
with QoS=1
, then closes connection.
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 sends a message on 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 reconnects and should see TxUser’s message
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" } }
Answer
OK I figured this out. Apparently, I just needed to add {qos:1}
in the publish statement within the send.js
script. So it should look like:
client.publish('Channel-01', '* * * IMPORTANT msg ' + Date() + ' * * *' , {qos:1}, function() {...etc
To clarify the MQTT.js introduction/demo slides, I submitted a PR to the author and the the updated slides are here.