/
nucleus.js
106 lines (95 loc) · 2.12 KB
/
nucleus.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
* nucleus
* <cam@onswipe.com>
*/
/*
* node discovery
* node drops
* heartbeating?
* emission broadcasting
* incoming emissions
*/
var os = require('os');
var ee2 = require('eventemitter2').EventEmitter2;
var net = require('net');
/*
* Create a new Nucleus object
* Parse options
* Trigger transport loading
*/
var Nucleus = function (options) {
options = options || {};
this.peers = [];
this._ = {};
this._.transport = options.redis ? 'redis' : 'mdns';
this.port = options.port || 42;
this.ee = new ee2();
this.createServer();
this.buildLocalAddresses();
this.loadTransport();
}
/*
* Pretend to be an EventEmitter
*/
Nucleus.prototype = require(__dirname + '/lib/events.js');
/*
* Load our advertisement transport
* Trigger browser
*/
Nucleus.prototype.loadTransport = function () {
var t = this._.transport;
this.transport = require(__dirname + '/transports/' + t);
this.transport.browse(this); // need to provide context to the transport
this.transport.advertise(this);
}
/*
* Compile an easily-searchable array
* of local addresses
*/
Nucleus.prototype.buildLocalAddresses = function () {
this._.addresses = [];
var interfaces = os.networkInterfaces();
for (var i in interfaces) {
for (var j in interfaces[i]) {
this._.addresses.push(
interfaces[i][j].address
);
}
}
}
/*
* Set up a TCP server to listen for Peer clients
*/
Nucleus.prototype.createServer = function () {
var that = this;
this.$ = net.createServer(this.connectionHandler);
this.$.listen(this.port, function () {
that.ee.emit('server.ready');
});
}
/*
* Handle a Peer client connecting to TCP server
*/
Nucleus.prototype.connectionHandler = function (socket) {
socket.on('data', function (data) {
console.log(data.toString());
});
socket.on('end', function () {
console.log('client disconnected');
console.log(arguments);
});
}
/*
* Write to all TCP Peer clients
*/
Nucleus.prototype.broadcast = function (data) {
for (var i in this.peers) {
if (this.peers[i].$.writable) {
this.peers[i].send(data);
}
}
}
/*
* Say cheese
*/
module.exports = Nucleus;