forked from michaljaz/webmc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.js
More file actions
38 lines (35 loc) · 1 KB
/
Socket.js
File metadata and controls
38 lines (35 loc) · 1 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
import { encode, decode, decodeAsync } from "@msgpack/msgpack";
class Socket {
constructor(game, url) {
this.game = game;
this.ws = new WebSocket(url);
this.handlers = new Map();
this.ws.onmessage = async (message) => {
try {
const [type, ...data] = await this.decodeFromBlob(message.data);
const handler = this.handlers.get(type);
handler && handler(...data);
} catch (err) {
console.log(err);
}
};
}
emit(type, ...data) {
this.ws.send(
encode([
type,
...data.filter((d) => typeof d !== "function"), // Temp solution
])
);
}
on(type, handler) {
this.handlers.set(type, handler);
}
async decodeFromBlob(blob) {
if (blob.stream) {
return await decodeAsync(blob.stream());
}
return decode(await blob.arrayBuffer());
}
}
export { Socket };