-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerConnection.js
55 lines (49 loc) · 1.35 KB
/
ServerConnection.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
export class ServerConnection {
#socket = null;
#pendingMessages = new Set();
constructor(onConnected, onDisconnected, onMessage) {
this.onConnected = onConnected;
this.onDisconnected = onDisconnected;
this.onMessage = onMessage;
}
isConnected() {
return this.#socket != null;
}
connect(url) {
this.#socket = new WebSocket(url);
this.#socket.onopen = (event) => {
if (this.onConnected) {
this.onConnected(this.#socket);
}
console.log('WebSocket opened');
};
this.#socket.onclose = (event) => {
this.#socket = null;
console.log('WebSocket closed with code ' + event.code + ' and reason: ' + event.reason);
if (this.onDisconnected) {
this.onDisconnected();
}
}
this.#socket.onerror = (event) => {
console.log('WebSocket error: ' + event);
}
this.#socket.onmessage = (event) => {
const message = event.data.arrayBuffer();
this.#pendingMessages.add(message);
Promise.all(this.#pendingMessages).then((values) => {
this.#pendingMessages.delete(message);
this.onMessage(new DataView(values[values.length - 1]));
});
}
}
send(msg) {
if (this.#socket != null) {
this.#socket.send(msg.getBuffer());
}
}
disconnect() {
if (this.#socket != null) {
this.#socket.close();
}
}
};