Created
November 27, 2019 09:10
-
-
Save toygame/5c7aab9bf63ca271ba330da7230934fe to your computer and use it in GitHub Desktop.
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
var mqtt = require('mqtt'); | |
const MQTT_SERVER = "Your Server Address"; | |
const MQTT_PORT = "1883"; | |
//if your server don't have username and password let blank. | |
const MQTT_USER = ""; | |
const MQTT_PASSWORD = ""; | |
// Connect MQTT | |
var client = mqtt.connect({ | |
host: MQTT_SERVER, | |
port: MQTT_PORT, | |
username: MQTT_USER, | |
password: MQTT_PASSWORD | |
}); | |
client.on('connect', function () { | |
// Subscribe any topic | |
console.log("MQTT Connect"); | |
client.subscribe('test', function (err) { | |
if (err) { | |
console.log(err); | |
} | |
}); | |
}); | |
// Receive Message and print on terminal | |
client.on('message', function (topic, message) { | |
// message is Buffer | |
console.log(message.toString()); | |
}); | |
setInterval(() => { | |
client.publish("test", "hello from NodeJS"); | |
}, 5000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment