This repository has been archived on 2026-03-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
cau-praktikum/app/static/js/ws.js
T

36 lines
948 B
JavaScript

// using socketio for websocket communication
export function createWSClient(handlers = {}) {
const socket = io();
socket.on("connect", () => {
console.log("Connected to server");
handlers.onConnect?.();
});
socket.on("disconnect", () => {
console.log("Disconnected from server");
handlers.onDisconnect?.();
});
const serverEvents = {
code_game_created: handlers.onGameCreated,
code_game_joined: handlers.onGameJoined,
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
};
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");
}