BlueGit

timfa questward

Files

questward / client / src / net / socket.js

socket.js

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