forked from bigeasy/udt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
43 lines (37 loc) · 1.36 KB
/
server.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
const endpoint = require('./endpoint')
, events = require('events');
// Events emitted by Server:
// 'close' - Server has been shut down
// 'connection' - A new client connection was established (after handshaking). Returns a socket you can use.
// 'error' - With exception parameter attached
// 'listening' - Server is now listening on requested port and address for incoming connections
module.exports = class Server extends events.EventEmitter {
constructor() {
super();
this.connections = 0;
}
listen(address, onConnect, onListening) {
var server = this;
server.on('connection', onConnect);
server.once('listening', onListening);
endpoint.createEndPoint(address, (endPoint) => {
server._endPoint = endPoint;
server.address = endPoint.address;
process.nextTick(() => { server.emit('listening'); });
// pass on up endpoint events
server._endPoint.on('connection', (socket) => {
server.emit('connection', socket);
});
});
}
close(callback) {
if (callback) this.once('close', callback);
this._closing = true;
if (this._endPoint.listeners == 0) {
this.emit('close'); // We can close immediately
}
}
address() {
return this._endPoint.address();
}
};