Created
July 9, 2017 10:49
-
-
Save dyaa/bf74eb36e9171735d7b01f84cb68575a to your computer and use it in GitHub Desktop.
MQTT nodejs connect
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'); | |
var url = "mqtts://localhost"; | |
var options = { | |
port: 8883, | |
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8), | |
username: '', | |
password: '', | |
}; | |
// Create a client connection | |
var client = mqtt.connect(url, options); | |
client.on('connect', function() { // When connected | |
// subscribe to a topic | |
client.subscribe('test', function() { | |
// when a message arrives, do something with it | |
client.on('message', function(topic, message, packet) { | |
console.log("Received '" + message + "' on '" + topic + "'"); | |
}); | |
}); | |
// publish a message to a topic | |
client.publish('test', 'my message', function() { | |
console.log("Message is published"); | |
client.end(); // Close the connection when published | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment