service-discovery
Version:
Simple network discovery based on UDP multicast
95 lines (85 loc) • 2.32 kB
text/coffeescript
dgram = require 'dgram'
{EventEmitter} = require 'events'
METHOD_NOTIFY = 'notify'
METHOD_FIND = 'find'
INTERVAL = 2000
MULTICAST_IP = '239.155.155.150'
MULTICAST_PORT = 22000
###
* Simple service discovery over UDP multicast
* Emits events with name of catched service description
* Custom event '*' catches all messages
###
class Listener extends EventEmitter
###
* Create new instance of service finder
* {function(Listener) } Ready callback
* {number} Multicast port
* {string} Multicast IP
###
constructor: (done, = MULTICAST_PORT, = MULTICAST_IP) ->
= dgram.createSocket('udp4')
.bind , () =>
.addMembership
done(this) if done
.on 'message',
###
* Listener for incoming UDP messages
###
on_message: (msg, rinfo) =>
msg = JSON.parse msg.toString()
ip = rinfo.address
msg.name, msg.name, ip, msg.data
'*', msg.name, ip, msg.data
###
* Close sockets and remove all listeners
* {Service} itself
###
close: () =>
.close()
return this
class Description
###
* Create new instance of service description
* {string} Name of service
* {number} Multicast port
* {string} Multicast IP
* {number} Sending interval
###
constructor: (, = MULTICAST_PORT, = MULTICAST_IP, interval = INTERVAL) ->
= {}
= dgram.createSocket('udp4')
= setInterval , interval
###
* Add attribute of description
* {string} Name of attribute.
* {object} Serializeable data
* {Service} itself
###
attr: (name, data) =>
[name] = data
return this
###
* Send self description to multicast group
* {Service} itself
###
notify: () =>
msg =
method: METHOD_NOTIFY
name:
data:
time: Date.now()
msg = new Buffer JSON.stringify(msg)
.send msg, 0, msg.length, ,
return this
###
* Close sockets and remove timer
* {Service} itself
###
close: () =>
.close()
clearInterval
return this
module.exports.Listener = Listener
module.exports.Description = Description