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
});
});