Skip to content

Instantly share code, notes, and snippets.

@nivertech
Forked from bergie/README.md
Created February 20, 2012 03:49
Show Gist options
  • Save nivertech/1867679 to your computer and use it in GitHub Desktop.
Save nivertech/1867679 to your computer and use it in GitHub Desktop.
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 = '127.0.0.1'
topic = 'persons/locations/bergie'
subsTopic = 'persons/locations/+'
payload =
person: 'Bergie'
isDoing: 'koodaamassa'
where: 'toimistolla'
sendMessage = (client) ->
client.publish
topic: topic
payload: JSON.stringify payload
subscribeTo = (client) ->
client.subscribe
topic: subsTopic
client.on 'publish', (packet) ->
console.log packet
mqtt.createClient port, host, (client) ->
client.connect
keepalive: 3000
client.on 'connack', (packet) ->
if packet.returnCode is 0
subscribeTo client
sendMessage client
else
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) ->
client.connack
returnCode: 0
client.id = packet.client
clients[client.id] = client
# Forward published packets to all clients
client.on 'publish', (packet) ->
for clientId, client of clients
console.log packet
client.publish
topic: packet.topic
payload: packet.payload
# Receive subscriptions
client.on 'subscribe', (packet) ->
granted = []
for subscription in packet.subscriptions
granted.push subscription.qos
client.suback
granted: granted
# Response to pings
client.on 'pingreq', (packet) ->
client.pingresp()
# Handle disconnects
client.on 'disconnect', (packet) ->
client.stream.end()
client.on 'close', (err) ->
delete clients[client.id]
client.on 'error', (err) ->
client.stream.end()
console.log "Error with #{client.id}"
server.listen 1883
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment