Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
MQTT pub/sub example

This is a simple example of the MQTT protocol with Node.js. The client code has also been tested with a combination of C++ servers and clients.

mqtt = require 'mqttjs'
port = 1883
host = ''
topic = 'persons/locations/bergie'
subsTopic = 'persons/locations/+'
payload =
person: 'Bergie'
isDoing: 'koodaamassa'
where: 'toimistolla'
sendMessage = (client) ->
topic: topic
payload: JSON.stringify payload
subscribeTo = (client) ->
topic: subsTopic
client.on 'publish', (packet) ->
console.log packet
mqtt.createClient port, host, (client) ->
keepalive: 3000
client.on 'connack', (packet) ->
if packet.returnCode is 0
subscribeTo client
sendMessage client
console.log "Connack error #{packet.returnCode}"
process.exit 1
client.on 'close', ->
process.exit 0
client.on 'error', (e) ->
console.log "Error #{e}"
process.exit 1
"name": "mqtt-example",
"version": "0.0.1",
"dependencies": {
"mqttjs": ">=0.1.3"
mqtt = require 'mqttjs'
# Holder for all clients
clients = {}
server = mqtt.createServer (client) ->
# Catch when client connects
client.on 'connect', (packet) ->
returnCode: 0 = packet.client
clients[] = client
# Forward published packets to all clients
client.on 'publish', (packet) ->
for clientId, client of clients
console.log packet
topic: packet.topic
payload: packet.payload
# Receive subscriptions
client.on 'subscribe', (packet) ->
granted = []
for subscription in packet.subscriptions
granted.push subscription.qos
granted: granted
# Response to pings
client.on 'pingreq', (packet) ->
# Handle disconnects
client.on 'disconnect', (packet) ->
client.on 'close', (err) ->
delete clients[]
client.on 'error', (err) ->
console.log "Error with #{}"
server.listen 1883
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment