Create functions for websockets
This commit is contained in:
parent
67f0e39777
commit
85c0e27a32
@ -9,31 +9,49 @@ enum LobbyStatus {
|
|||||||
Error,
|
Error,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const connectionRetryInterval = 5000;
|
||||||
|
|
||||||
export function Lobby() {
|
export function Lobby() {
|
||||||
const [status, setStatus] = createSignal(LobbyStatus.Connecting);
|
const [status, setStatus] = createSignal(LobbyStatus.Disconnected);
|
||||||
let ws: WebSocket|null = null;
|
let ws: WebSocket|null = null;
|
||||||
|
|
||||||
const lobbyConnect = async() => {
|
const lobbyConnect = () => {
|
||||||
|
setStatus(LobbyStatus.Connecting);
|
||||||
ws = new WebSocket(`${import.meta.env.VITE_WS_URL}/lobby/connect`);
|
ws = new WebSocket(`${import.meta.env.VITE_WS_URL}/lobby/connect`);
|
||||||
|
|
||||||
ws.addEventListener("open", () => {
|
ws.addEventListener("open", onWsOpen);
|
||||||
console.log("Connection open!");
|
ws.addEventListener("message", onWsMessage);
|
||||||
setStatus(LobbyStatus.Connected);
|
ws.addEventListener("error", onWsError);
|
||||||
});
|
ws.addEventListener("close", onWsClose);
|
||||||
|
};
|
||||||
|
|
||||||
ws.addEventListener("message", (ev) => {
|
const onWsOpen = () => {
|
||||||
console.log("message from ws!");
|
console.log("Connection open!");
|
||||||
console.log(ev);
|
setStatus(LobbyStatus.Connected);
|
||||||
});
|
|
||||||
|
|
||||||
ws.addEventListener("error", (ev) => {
|
// The first message must be authenticating with the server
|
||||||
console.error(ev);
|
};
|
||||||
setStatus(LobbyStatus.Error);
|
|
||||||
});
|
|
||||||
|
|
||||||
ws.addEventListener("close", () => {
|
const onWsMessage = (ev: MessageEvent) => {
|
||||||
console.log("connection closed");
|
console.log("message from ws!");
|
||||||
});
|
console.log(ev.data);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onWsError = (ev: Event) => {
|
||||||
|
console.error("error in connection");
|
||||||
|
console.error(ev);
|
||||||
|
setStatus(LobbyStatus.Error);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onWsClose = () => {
|
||||||
|
// If the previous state is "Error", we don't set
|
||||||
|
// the state to Disconnected
|
||||||
|
if (status() !== LobbyStatus.Error) {
|
||||||
|
setStatus(LobbyStatus.Disconnected);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`connection closed. reconnecting in ${connectionRetryInterval}ms`);
|
||||||
|
setTimeout(lobbyConnect, connectionRetryInterval);
|
||||||
};
|
};
|
||||||
|
|
||||||
const send = () => {
|
const send = () => {
|
||||||
|
Loading…
Reference in New Issue
Block a user