Migrate to "robust-websocket" to have more stable reconnect.
This commit is contained in:
parent
45e07d9393
commit
45f67d2cdf
3 changed files with 3 additions and 27 deletions
|
@ -21,6 +21,7 @@ fun HTML.createGameMasterDocument() {
|
|||
src = "https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"
|
||||
defer = true
|
||||
}
|
||||
script { src = "https://unpkg.com/robust-websocket@1.0.0/robust-websocket.js" }
|
||||
script { src = "/assets/buzzerWebSocket.js" }
|
||||
}
|
||||
body {
|
||||
|
|
|
@ -21,6 +21,7 @@ fun HTML.createPlayerDocument() {
|
|||
src = "https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"
|
||||
defer = true
|
||||
}
|
||||
script { src = "https://unpkg.com/robust-websocket@1.0.0/robust-websocket.js" }
|
||||
script {
|
||||
src = "/assets/buzzerWebSocket.js"
|
||||
}
|
||||
|
|
|
@ -2,33 +2,7 @@
|
|||
|
||||
function startWebSocket(socketPath, messageHandler) {
|
||||
const protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
|
||||
const webSocket = new WebSocket(`${protocolPrefix}//${location.host}${socketPath}`);
|
||||
webSocket.onerror = (ev) => {
|
||||
switch (ev.code) {
|
||||
case 1000:
|
||||
console.log("[WS]: Closed normally")
|
||||
break
|
||||
default:
|
||||
console.log("[WS]: Closed abnormally")
|
||||
reconnectWebSocket(socketPath, messageHandler);
|
||||
}
|
||||
};
|
||||
webSocket.onclose = (ev) => {
|
||||
switch (ev.code) {
|
||||
case 'ECONNREFUSED':
|
||||
reconnectWebSocket(socketPath, messageHandler);
|
||||
break
|
||||
default:
|
||||
webSocket.onerror(ev);
|
||||
}
|
||||
};
|
||||
const webSocket = new RobustWebSocket(`${protocolPrefix}//${location.host}${socketPath}`);
|
||||
webSocket.onmessage = messageHandler ? messageHandler : () => {};
|
||||
Alpine.data.buzzerWebSocket = webSocket
|
||||
}
|
||||
|
||||
function reconnectWebSocket(socketPath, messageHandler) {
|
||||
setTimeout(() => {
|
||||
console.log("[WS]: Reconnecting...")
|
||||
startWebSocket(socketPath, messageHandler)
|
||||
}, 2000)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue