Repository navigation
Expand file tree
/
Copy pathsocket.ts
More file actions
103 lines (79 loc) · 1.91 KB
/
Copy pathsocket.ts
File metadata and controls
103 lines (79 loc) · 1.91 KB
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
99
100
101
102
103
import { Packet } from './common/protocol';
interface Events {
data: (packet: Packet) => void;
reconnect: () => void;
}
interface Socket {
sendPacket(packet: Packet): void;
on<K extends keyof Events>(eventType: K, handler: Events[K]): void;
}
const stub = () => void 0;
/**
* Lightweight websocket abstraction
* @param url URL of the terminal handler
*/
function initSocket(url: string) {
return new Promise<Socket>((resolve) => {
const eventHandlers: Events = {
data: stub,
reconnect: stub,
};
let resolved = false;
console.log('Opening Websocket', url);
let ws: WebSocket | null;
connect();
function connect() {
ws = new WebSocket(url);
ws.onmessage = onMessage;
ws.onopen = onOpen;
ws.onclose = onClose;
ws.onerror = onError;
}
function onMessage(evt: MessageEvent) {
if (typeof evt.data === 'string') {
const packet: Packet = JSON.parse(evt.data);
eventHandlers.data(packet);
} else {
throw new Error('Unexpected data type');
}
}
function onOpen() {
if (!resolved) {
resolve({
sendPacket,
on,
});
resolved = true;
} else {
eventHandlers.reconnect();
}
}
function onClose() {
ws = null;
console.info('CLOSED');
attemptReconnect();
}
function onError(evt: Event) {
console.error('socket', evt);
}
function attemptReconnect() {
setTimeout(() => {
console.info('RECONNECT');
connect();
}, 1000);
}
function sendPacket(packet: Packet) {
if (!ws) {
console.log('sendPacket: Socket not available');
return;
}
ws.send(JSON.stringify(packet));
}
function on<K extends keyof Events>(eventType: K, handler: Events[K]) {
eventHandlers[eventType] = handler;
}
});
}
export {
initSocket,
};