1

my code is as shown below:

var mqtt = require('mqtt'), url = require('url');
var url = "mqtt://cloudamqp_username:cloudamqp_password@hostname:port";

var options = {
    port: 1883,
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: 'cloudamqp_username',
    password: 'cloudamqp_password'
};


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
    });
});
Mrugesh
  • 4,381
  • 8
  • 42
  • 84

0 Answers0