Skip to content

Instantly share code, notes, and snippets.

@id
Created February 21, 2024 14:20
Show Gist options
  • Save id/2f75989bd2b958325620084e7f1e560b to your computer and use it in GitHub Desktop.
Save id/2f75989bd2b958325620084e7f1e560b to your computer and use it in GitHub Desktop.
mqtt.js sample code
const mqtt = require("mqtt");
const url = 'mqtts://127.0.0.1:8883'
const options = {
clean: true,
connectTimeout: 1000,
clientId: 'emqx_test',
username: 'emqx_test',
password: 'emqx_test',
rejectUnauthorized: false,
}
const client = mqtt.connect(url, options)
console.log('Connecting to', url)
client.on('connect', function () {
console.log(new Date().toISOString(), 'Connected')
client.subscribe('test', function (err) {
if (!err) {
client.publish('test', 'hello')
}
})
})
client.on('message', function (topic, message) {
console.log(new Date().toISOString(), 'Received: ' + message.toString())
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment