Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: retained message config example #967

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions examples/client/both-with-retain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict'

var mqtt = require('../..')

// Subscribe to a custom server with a URL string
var client = mqtt.connect('mqtt://test.mosquitto.org:1883')

client.subscribe('presence-retained', { qos: 1 })
client.on('message', function (topic, message) {
console.log(`Received on '${topic}': ${message.toString()}`)
})

/* Sends the message 'hello!' to the topic 'presence'. The message will be delivered
* at least once to clients even if they subscribe later.
* If compiling TypeScript, the options object must include the qos property
* to be recognized as an instance of IClientPublishOptions (and not the callback).
* Remaining properties are optional.
*/
client.on('connect', function (topic, message) {
console.log('Connected')
client.publish('presence-retained', 'hello!', {qos: 1, retain: true},
(err) => {
if (err) {
console.log('There was an error sending the message.')
return
}
console.log('QoS handling completed')
}
)

// Clear the retained message when no longer needed:
setTimeout(() => {
client.publish('presence-retained', '', {qos: 0, retain: true})
client.end() // Exits this example
}, 5000)
})
Loading