mqtt-test.js
javascript
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://127.0.0.1')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
mqtt-server.js
javascript
var mosca = require('mosca')
var settings = {
port: 1883,
backend: {},
}
var server = new mosca.Server(settings)
server.on('clientConnected', function (client) {
console.log('client connected', client.id)
})
server.on('published', function (packet, client) {
console.log('Published', packet.payload)
})
server.on('ready', setup)
function setup() {
console.log('Mosca server is up and running')
}
package.json
json
{
"name": "mqtt-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mosca": "^2.8.3",
"mqtt": "^3.0.0"
}
}