-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockets.js
44 lines (35 loc) · 1.05 KB
/
websockets.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
const EventEmitter = require('events');
const ws = require('ws');
class SocketWrapper extends EventEmitter {
constructor(socket) {
super();
this.socket = socket;
this._localEmit = EventEmitter.prototype.emit.bind(this);
socket.on('message', message => {
const {name, data} = JSON.parse(message);
this._localEmit(name, data);
});
socket.on('close', () => {
this._localEmit('close');
});
}
emit(name, data) {
this.socket.send(JSON.stringify({name, data}));
}
}
class ServerWrapper extends EventEmitter {
constructor(server) {
super();
this.server = server;
server.on('connection', socket => {
const socketWrapper = new SocketWrapper(socket);
this.emit('connection', socketWrapper);
});
}
}
function websocketFactory(config) {
const websocket = new ws.Server(config);
const serverWrapper = new ServerWrapper(websocket);
return serverWrapper;
}
module.exports = websocketFactory;