mqtt-test.js

  1. var mqtt = require("mqtt");
  2. var client = mqtt.connect("mqtt://127.0.0.1");
  3. client.on("connect", function() {
  4. client.subscribe("presence");
  5. client.publish("presence", "Hello mqtt");
  6. });
  7. client.on("message", function(topic, message) {
  8. // message is Buffer
  9. console.log(message.toString());
  10. client.end();
  11. });

mqtt-server.js

  1. var mosca = require("mosca");
  2. var settings = {
  3. port: 1883,
  4. backend: {}
  5. };
  6. var server = new mosca.Server(settings);
  7. server.on("clientConnected", function(client) {
  8. console.log("client connected", client.id);
  9. });
  10. server.on("published", function(packet, client) {
  11. console.log("Published", packet.payload);
  12. });
  13. server.on("ready", setup);
  14. function setup() {
  15. console.log("Mosca server is up and running");
  16. }

package.json

  1. {
  2. "name": "mqtt-test",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "author": "",
  10. "license": "ISC",
  11. "dependencies": {
  12. "mosca": "^2.8.3",
  13. "mqtt": "^3.0.0"
  14. }
  15. }