comparison web/websocket.js @ 2376:4556eebe5d73

topdir reorgs; let pdm have its src/ dir; separate vite area from light9/
author drewp@bigasterisk.com
date Sun, 12 May 2024 19:02:10 -0700
parents light9/web/websocket.js@19c2e6216cf8
children
comparison
equal deleted inserted replaced
2375:623836db99af 2376:4556eebe5d73
1 /*
2 url is now relative to the window location. Note that nginx may drop
3 the connection after 60sec of inactivity.
4 */
5
6 class ReconnectingWebsocket {
7
8 constructor(url, onMessage) {
9 this.onMessage = onMessage;
10 this.ws = null;
11 this.connectTimer = null
12 this.pong = 0;
13
14 this.fullUrl = (
15 "ws://"
16 + window.location.host
17 + window.location.pathname
18 + (window.location.pathname.match(/\/$/) ? "" : "/")
19 + url);
20 this.connect();
21 }
22 setStatus(txt) {
23 const docStatus = document.querySelector('#status')
24 if (docStatus) {
25 docStatus.innerText = txt;
26 }
27 }
28 connect() {
29 this.reconnect = true;
30 this.ws = new WebSocket(this.fullUrl);
31
32 this.ws.onopen = () => { this.setStatus("connected"); };
33 this.ws.onerror = (e) => { this.setStatus("error: "+e); };
34 this.ws.onclose = () => {
35 this.pong = 1 - this.pong;
36 this.setStatus("disconnected (retrying "+(this.pong ? "😼":"😺")+")");
37 this.ws = null;
38
39 this.connectTimer = setTimeout(() => {
40 this.connectTimer = null;
41 requestAnimationFrame(() => {
42 if (this.reconnect) {
43 this.connect();
44 }
45 });
46 }, 2000);
47 };
48 this.ws.onmessage = (evt) => {
49 this.onMessage(JSON.parse(evt.data));
50 };
51 }
52 disconnect() {
53 this.reconnect = false;
54 this.ws.close();
55 }
56 }
57
58
59
60 function reconnectingWebSocket(url, onMessage) {
61 return new ReconnectingWebsocket(url, onMessage);
62 }