-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathwebsocket.ts
98 lines (82 loc) · 2.35 KB
/
websocket.ts
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
import Promise from 'bluebird';
import EventEmitter from './misc/event-emitter';
class Websocket extends EventEmitter {
// @ts-ignore
private ws: WebSocket;
open(address: string, protocol: string): Promise<Websocket> {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(address, protocol ?? '');
this.ws.onerror = reject;
this.ws.onclose = reject;
this.ws.onopen = () => {
this.ws.onerror = () => {};
this.ws.onclose = () => {};
this.onOpen(this.ws);
resolve(this);
};
});
}
isOpened(): boolean {
return this.ws && this.ws.OPEN === this.ws.readyState;
}
isClosed(): boolean {
return !this.ws || this.ws.CLOSED === this.ws.readyState || this.ws.CLOSING === this.ws.readyState;
}
close(): Promise<void> {
if (this.isClosed()) return Promise.resolve();
return new Promise(resolve => {
this.onClose();
resolve();
});
}
send(message: any): Promise<void> {
if (this.isOpened()) {
return this.onSend(message);
} else if (!this.ws || this.ws.CONNECTING === this.ws.readyState) {
return this.queue(message);
} else {
return Promise.reject(new Error('Can not send message over closed connection'));
}
}
onMessage(message: any) {
try {
this.emit('message', message);
} catch (error) {
this.emit('error', error);
}
}
private queue(message: any): Promise<void> {
return new Promise(resolve => {
this.once('open', () => this.onSend(message).then(() => resolve()));
});
}
private onSend(message: any): Promise<void> {
return new Promise(resolve => {
this.ws.send(JSON.stringify(message));
resolve();
});
}
private onClose() {
if (!this.isClosed()) {
this.ws.close();
}
this.emit('close');
}
private initListeners() {
this.ws.onmessage = msg => {
let parsed = JSON.parse(msg.data as string);
this.onMessage(parsed);
};
this.ws.onerror = error => this.emit('error', error);
this.ws.onclose = () => this.onClose();
}
private onOpen(webSocket: WebSocket) {
if (typeof webSocket.readyState !== 'undefined') {
this.initListeners();
} else {
throw new Error('Trying to instantiate WebsocketConnection with unknown Websocket.');
}
this.emit('open');
}
}
export default Websocket;