A good javascript MQTT library is MQTT.js. Add mqtt to your package.json file. A simple example using MQTT.js is shown below.
CloudAMQP MQTT URL Structure mqtt://cloudamqp_username:cloudamqp_password@hostname:port
var mqtt = require('mqtt'), url = require('url');
// Parse
var mqtt_url = url.parse(process.env.CLOUDAMQP_MQTT_URL || 'mqtt://localhost:1883');
var auth = (mqtt_url.auth || ':').split(':');
var url = "mqtt://" + mqtt_url.host;
//username: auth[0] + ":" + auth[0] if you are on a shared instance
var options = {
port: mqtt_url.port,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: auth[0],
password: auth[1],
};
// Create a client connection
var client = mqtt.connect(url, options);
client.on('connect', function() { // When connected
// subscribe to a topic
client.subscribe('hello/world', 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('hello/world', 'my message', function() {
console.log("Message is published");
client.end(); // Close the connection when published
});
});
A full sample web app which uses MQTT.js, Express.js and SSE to deliver messages from and to a web browser is available here: github.com/CloudMQTT/mqtt-sse and can be tested out here at mqtt-sse.herokuapp.com.