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
53 lines (50 loc) · 1.49 KB
/
Socket.js
File metadata and controls
53 lines (50 loc) · 1.49 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
import { encode, decode, decodeAsync } from "@msgpack/msgpack";
import swal from "sweetalert";
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);
}
};
this.ws.onclose = () => {
console.log("Lost connection!");
swal({
title: "You have lost connection!",
text: "Websocket connection have been closed!",
icon: "error",
button: "Rejoin",
}).then(function () {
document.location.reload();
});
};
this.ws.onerror = (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 };