public
Created

MQTT pub/sub example

  • Download Gist
README.md
Markdown

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.

client.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
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
package.json
JSON
1 2 3 4 5 6 7
{
"name": "mqtt-example",
"version": "0.0.1",
"dependencies": {
"mqttjs": ">=0.1.3"
}
}
server.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.