finish ws client & handlers

This commit is contained in:
2026-02-27 12:15:04 +01:00
parent 82e3787656
commit 73a474b428
2 changed files with 42 additions and 11 deletions
+7 -8
View File
@@ -1,35 +1,34 @@
// using socketio for websocket communication
export function createWSClient(handlers = {}) {
const socket = io();
socket.on("connect", () => {
console.log("Connected to server");
handlers.onConnect?.();
handlers.onConnect?.(socket);
});
socket.on("disconnect", () => {
console.log("Disconnected from server");
handlers.onDisconnect?.();
});
const serverEvents = {
server_ready: handlers.onServerReady,
code_game_created: handlers.onGameCreated,
code_game_joined: handlers.onGameJoined,
code_game_join_failed: handlers.onGameJoinFailed,
game_started: handlers.onGameStarted,
p2_connected: handlers.onP2Connected,
user_move: handlers.onUserMove,
move_accept: handlers.onMoveAccept,
move_reject: handlers.onMoveReject,
game_over: handlers.onGameOver,
//todo: draw, resign, rematch
draw_offer: handlers.onDrawOffered,
clock_tick: handlers.onClockTick,
};
let i = 0;
for (const [event, handler] of Object.entries(serverEvents)) {
if (handler) {
socket.on(event, handler);
i++;
}
}
console.log("registered " + i + " server event handlers");
return socket;
}