Create functions for websockets
This commit is contained in:
parent
67f0e39777
commit
85c0e27a32
@ -9,31 +9,49 @@ enum LobbyStatus {
|
||||
Error,
|
||||
}
|
||||
|
||||
const connectionRetryInterval = 5000;
|
||||
|
||||
export function Lobby() {
|
||||
const [status, setStatus] = createSignal(LobbyStatus.Connecting);
|
||||
const [status, setStatus] = createSignal(LobbyStatus.Disconnected);
|
||||
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.addEventListener("open", () => {
|
||||
ws.addEventListener("open", onWsOpen);
|
||||
ws.addEventListener("message", onWsMessage);
|
||||
ws.addEventListener("error", onWsError);
|
||||
ws.addEventListener("close", onWsClose);
|
||||
};
|
||||
|
||||
const onWsOpen = () => {
|
||||
console.log("Connection open!");
|
||||
setStatus(LobbyStatus.Connected);
|
||||
});
|
||||
|
||||
ws.addEventListener("message", (ev) => {
|
||||
// The first message must be authenticating with the server
|
||||
};
|
||||
|
||||
const onWsMessage = (ev: MessageEvent) => {
|
||||
console.log("message from ws!");
|
||||
console.log(ev);
|
||||
});
|
||||
console.log(ev.data);
|
||||
};
|
||||
|
||||
ws.addEventListener("error", (ev) => {
|
||||
const onWsError = (ev: Event) => {
|
||||
console.error("error in connection");
|
||||
console.error(ev);
|
||||
setStatus(LobbyStatus.Error);
|
||||
});
|
||||
};
|
||||
|
||||
ws.addEventListener("close", () => {
|
||||
console.log("connection closed");
|
||||
});
|
||||
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 = () => {
|
||||
|
Loading…
Reference in New Issue
Block a user