-
Notifications
You must be signed in to change notification settings - Fork 0
/
pump.websocket.ts
50 lines (39 loc) · 1 KB
/
pump.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
/**
* The following code is only for demonstration purpose.
*
* DO NOT use it in production.
*/
import { ComcatPump } from 'comcat';
class WebsocketPump {
private readonly pump: ComcatPump;
private ws: WebSocket | null = null;
public constructor() {
this.pump = new ComcatPump({
category: 'example',
});
this.pump.onConnect = this.onConnect.bind(this);
this.pump.onDisconnect = this.onDisconnect.bind(this);
}
public start() {
this.pump.start();
}
private onConnect() {
return new Promise((resolve, reject) => {
const ws = new WebSocket('wss://example.com/');
ws.onopen = () => resolve(true);
ws.onerror = () => reject();
ws.onmessage = this.onMessage.bind(this);
this.ws = ws;
});
}
private onDisconnect() {
this.ws.close();
this.ws = null;
}
private onMessage(event: MessageEvent<any>) {
const message = event.data;
this.pump.pump('example', message);
}
}
const pump = new WebsocketPump();
pump.start();