Skip to content

Instantly share code, notes, and snippets.

@toygame
Created November 27, 2019 09:10
Show Gist options
  • Save toygame/5c7aab9bf63ca271ba330da7230934fe to your computer and use it in GitHub Desktop.
Save toygame/5c7aab9bf63ca271ba330da7230934fe to your computer and use it in GitHub Desktop.
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