diff options
| author | Leonardo Bishop <me@leonardobishop.com> | 2023-11-04 21:28:11 +0000 |
|---|---|---|
| committer | Leonardo Bishop <me@leonardobishop.com> | 2023-11-04 21:28:11 +0000 |
| commit | 7d8cca54e548d2a85287fd2325db88f2697be55a (patch) | |
| tree | 3daa82c6a709363f2f08d9f875d849e4babe1f8f /backend/src/websocket/game.ts | |
| parent | e1633f3348ff7fc5e9131eeae2f2feba09f04838 (diff) | |
Add more shit
Diffstat (limited to 'backend/src/websocket/game.ts')
| -rw-r--r-- | backend/src/websocket/game.ts | 95 |
1 files changed, 95 insertions, 0 deletions
diff --git a/backend/src/websocket/game.ts b/backend/src/websocket/game.ts new file mode 100644 index 0000000..63c537a --- /dev/null +++ b/backend/src/websocket/game.ts @@ -0,0 +1,95 @@ +import { Server } from "http"; +import { addSessionClient, getSession, setSessionHost } from "../config/session-store.js"; +import { WebSocketServer } from "ws"; +import { v4 as uuidv4 } from "uuid"; + +const wss = new WebSocketServer({ noServer: true }); + +const sendToClient = (clientId: string, message: any) => { + wss.clients.forEach((client: any) => { + if (client.clientId === clientId) { + client.send(JSON.stringify(message)); + } + }); +}; + +const broadcastToClients = (clientIds: string[], message: any) => { + wss.clients.forEach((client: any) => { + if (clientIds.includes(client.clientId)) { + client.send(JSON.stringify(message)); + } + }); +}; + +export const createWebsocketServer = (server: Server): WebSocketServer => { + server.on("upgrade", (req, socket, head) => { + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit("connection", ws, req); + }); + }); + + wss.on("connection", (ws: any) => { + ws.clientId = uuidv4(); + + ws.on("message", (message) => { + console.log("received: %s", message); + let data; + try { + data = JSON.parse(message.toString()); + } catch (e) { + console.log("Invalid JSON"); + return; + } + + if (data.action === "host") { + setSessionHost(data.sessionId, ws.clientId); + } else if (data.action === "move") { + const session = getSession(data.sessionId); + if (!session) { + return; + } + + sendToClient(session.host!, { + action: "move", + move: data.move, + }); + } else if (data.action === "join") { + const session = getSession(data.sessionId); + if (!session) { + return; + } + + addSessionClient(data.sessionId, ws.clientId); + + sendToClient(session.host!, { + action: "join", + clients: session.clients.length, + }); + + ws.send(JSON.stringify({ + action: "state", + state: session.state, + })); + } else if (data.action === "start") { + const session = getSession(data.sessionId); + if (!session) { + return; + } + + sendToClient(session.host!, { + action: "state", + state: "playing", + }); + + broadcastToClients(session.clients, { + action: "state", + state: "playing", + }); + } + }); + }); + + return wss; +}; + +export default createWebsocketServer; |
