-
Notifications
You must be signed in to change notification settings - Fork 1
/
ews.js
85 lines (70 loc) · 2.02 KB
/
ews.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
let {ExChannel, RemoteError} = require('exchannel');
let {EventEmitter} = require('events');
let RealWebSocket = require('ws');
function newCall(Cls, args) {
args.unshift(null);
return new (Function.prototype.bind.apply(Cls, args));
}
class WebSocket extends ExChannel {
constructor(firstArg, ...args) {
let wsClient;
if(firstArg && firstArg instanceof RealWebSocket) {
wsClient = firstArg;
} else {
wsClient = new RealWebSocket(firstArg, ...args);
}
super(wsClient);
this.responseTimeout = 10000;
this.wsClient = wsClient;
this.wsClient.on('open', () => {
this.emit('open');
});
this.wsClient.on('close', () => {
this.emit('close');
});
this.wsClient.on('error', err => {
this.emit('error', err);
});
}
isClosed() {
return this.wsClient.readyState === RealWebSocket.CLOSED ||
this.wsClient.readyState === RealWebSocket.CLOSING;
}
close() {
this.wsClient.close.apply(this.wsClient, arguments);
}
terminate() {
this.wsClient.terminate();
}
}
class WebSocketServer extends EventEmitter {
constructor() {
super();
let args = Array.prototype.slice.call(arguments);
EventEmitter.call(this);
this.wsServer = newCall(RealWebSocket.Server, args);
this.wsServer.on('connection', ws => {
let ewsSocket = new WebSocket(ws);
ewsSocket.server = this;
this.emit('connection', ewsSocket);
});
let forwardEventsFor = eventName => {
this.wsServer.on(eventName, () => {
let args = Array.prototype.slice.call(arguments);
args.unshift(eventName);
this.emit.apply(this, args);
});
};
forwardEventsFor('listening');
}
}
function forwardCallServer(name) {
WebSocketServer.prototype[name] = function() {
this.wsServer[name].apply(this.wsServer, arguments);
};
}
forwardCallServer('close');
WebSocket.Server = WebSocketServer;
WebSocket.RemoteError = RemoteError;
WebSocket.RequestHandler = ExChannel;
module.exports = WebSocket;