BlueGit

timfa questward

Files

questward / client / src / net / socket.js

socket.js

socket.js 872 B Download Raw
1export class GameSocket
2{
3 constructor (url, onMessage, { onClose } = {})
4 {
5 this.url = url;
6 this.onMessage = onMessage;
7 this.onClose = onClose;
8 this.socket = null;
9 }
10
11 connect ()
12 {
13 this.socket = new WebSocket(this.url);
14 this.socket.addEventListener("message", (event) =>
15 {
16 this.onMessage(JSON.parse(event.data));
17 });
18 this.socket.addEventListener("close", (event) =>
19 {
20 this.onClose?.(event);
21 });
22 return new Promise((resolve, reject) =>
23 {
24 this.socket.addEventListener("open", resolve, { once: true });
25 this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });
26 });
27 }
28
29 send (payload)
30 {
31 this.socket.send(JSON.stringify(payload));
32 }
33}
34
35export function defaultSocketUrl ()
36{
37 const protocol = location.protocol === "https:" ? "wss:" : "ws:";
38 return `${protocol}//${location.host}/ws`;
39}