How to connect MQTT connection with Node.js
Connection Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
var mqtt = require('mqtt'); var options = { port: 1883, host: 'mqtt://m.dominname.com', clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8), username: 'username', password: 'password', keepalive: 60, reconnectPeriod: 1000, protocolId: 'MQIsdp', protocolVersion: 3, clean: true, encoding: 'utf8' }; var client = mqtt.connect('mqtt://m.dominname.com',options); |
Subscribe and Publish Data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
client.on('connect', function() { console.log('Connected MQTT'); client.subscribe("TOPICNAME"); }); client.on('message', function(topic, message) { console.log(topic); console.log(message); }); client.publish("TOPICNAME", "COMMAND"); |
More Stories
Configuring Apache for Node.js
Video streaming using Node.js and HTML5
Stream audio from the microphone