Skip to content

Instantly share code, notes, and snippets.

@dyaa
Created July 9, 2017 10:49
Show Gist options
  • Save dyaa/bf74eb36e9171735d7b01f84cb68575a to your computer and use it in GitHub Desktop.
Save dyaa/bf74eb36e9171735d7b01f84cb68575a to your computer and use it in GitHub Desktop.
MQTT nodejs connect
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