From c7e7ac4746ce39462d3ed31cea417d496feee23f Mon Sep 17 00:00:00 2001 From: Thilo Behnke Date: Tue, 21 Jun 2022 19:58:16 +0200 Subject: [PATCH] create event websocket --- client/svelte-client/src/api/session.ts | 36 ++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/client/svelte-client/src/api/session.ts b/client/svelte-client/src/api/session.ts index 65549be..7bf1fc4 100644 --- a/client/svelte-client/src/api/session.ts +++ b/client/svelte-client/src/api/session.ts @@ -1,4 +1,4 @@ -import type {LocalSession, Player, Session} from "../store/session"; +import type {LocalSession, Session} from "../store/session"; import {SessionState, SessionType} from "../store/session"; async function createLocalSession(): Promise { @@ -38,6 +38,40 @@ async function watchNetworkSession(sessionId): Promise { }); } +async function createEventWebsocket(session: Session): Promise { + return new Promise((res, rej) => { + if (session.type === SessionType.LOCAL) { + return rej("Websocket not allowed for local session!"); + } + const url = `pong/ws?session_id=${session.session_id}&connection_type=${session.type.toLowerCase()}`; + return createWebsocket(url); + }) +} + +async function createWebsocket(path: string): Promise { + return new Promise((res, rej) => { + const baseUrl = location.host.split(':')[0]; + const websocket = new WebSocket(`ws://${baseUrl}/${path}`); + waitForWebsocket(websocket, 10, () => { + return res(websocket) + }, () => rej()) + }) +} + +const waitForWebsocket = (websocket, retries, success, fail) => { + if (retries <= 0) { + console.error("Websocket not established successfully") + return + } + if(websocket.readyState !== 1) { + setTimeout(() => { + waitForWebsocket(websocket, retries - 1, success, fail) + }, 100) + } else { + success() + } +} + export default { createLocalSession, createNetworkSession,