websocket stuff

This commit is contained in:
Adam 2024-10-17 00:00:36 -04:00
parent 046504a15e
commit 914e71b231

View file

@ -1,8 +1,39 @@
import Joi from "joi";
import { JSXElement } from "solid-js";
import { onCleanup } from "solid-js";
import { createEffect, createSignal, onCleanup } from "solid-js";
export function Websocket(): JSXElement {
export function Websocket() {
const socket = new WebSocket("ws://127.0.0.1:3030/websocket");
// Signals
let [connected, set_connected] = createSignal(false);
let [users_count, set_users_count] = createSignal(null);
let [games_count, set_games_count] = createSignal(null);
let [active_games, set_active_games] = createSignal(null);
let [user_update, set_user_update] = createSignal(null);
let [chat_update, set_chat_update] = createSignal(null);
let [judge_round, set_judge_round] = createSignal(null);
let [chat_message, set_chat_message] = createSignal(null);
let [game_meta, set_game_meta] = createSignal(null);
let [game_state, set_game_state] = createSignal(null);
let [card_packs_meta, set_card_packs_meta] = createSignal(null);
// Wipe everything on disconnect
createEffect(() => {
if (!connected()) {
set_users_count(null);
set_games_count(null);
set_active_games(null);
set_user_update(null);
set_chat_update(null);
set_judge_round(null);
set_chat_message(null);
set_game_meta(null);
set_game_state(null);
set_card_packs_meta(null);
}
});
// Incoming message types
const UserUpdate = Joi.object({
username: Joi.string(),
});
@ -33,8 +64,7 @@ export function Websocket(): JSXElement {
unofficial_meta: Joi.array(),
});
const socket = new WebSocket("ws://127.0.0.1:3030/websocket");
// Message handler
const handleMessage = (event: MessageEvent) => {
let json = JSON.parse(event.data);
@ -76,21 +106,24 @@ export function Websocket(): JSXElement {
};
socket.addEventListener("message", handleMessage);
// Close handler
const handleClose = (event: CloseEvent) => {
console.log(
"The connection has been closed successfully.",
event.code,
event.reason,
);
set_connected(false);
console.log("Disconnected from websocket", event.code, event.reason);
};
socket.addEventListener("close", handleClose);
// Open handler
const handleOpen = () => {
set_connected(true);
console.log("Connected to websocket");
};
socket.addEventListener("open", handleOpen);
// Cleanup
onCleanup(() => {
socket.removeEventListener("message", handleMessage);
socket.removeEventListener("close", handleClose);
socket.close();
});
return <>SockEt</>;
}