-
Notifications
You must be signed in to change notification settings - Fork 0
/
host.js
40 lines (32 loc) · 900 Bytes
/
host.js
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
var net = require('net')
var split = require('split2')
var events = require('events')
var sock = net.connect(process.env.MN_SOCK)
sock.write(process.env.MN_HEADER + '\n')
sock.pipe(split()).on('data', function (data) {
try {
data = JSON.parse(data)
} catch (err) {
return
}
var opts = {from: data.from}
exports.emit('message', data.name, data.data, opts)
exports.emit('message:' + data.name, data.data, opts)
})
exports = module.exports = new events.EventEmitter()
exports.unref = function () {
sock.unref()
}
exports.ref = function () {
sock.ref()
}
exports.send = function (name, data, opts) {
if (!opts) opts = {}
sock.write(JSON.stringify({name: name, data: data, to: opts.to}) + '\n')
}
exports.sendTo = function (host, name, data) {
exports.send(name, data, {to: host})
}
exports.broadcast = function (name, data) {
exports.send(name, data, {to: '*'})
}