BlueGit

timfa questward

Files

questward / client / src / net / socket.js

socket.js

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