Created
February 21, 2024 14:20
-
-
Save id/2f75989bd2b958325620084e7f1e560b to your computer and use it in GitHub Desktop.
mqtt.js sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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