From 69705ce61ca6140eaf4a79be8c51993b33b8e1cc Mon Sep 17 00:00:00 2001 From: FernandoJVideira <03.pleaser-minster@icloud.com> Date: Thu, 11 Dec 2025 21:02:02 +0000 Subject: [PATCH] feat: websocket init --- websockets/.env.example | 1 + websockets/events/connection.js | 45 +++++++++++++++++++++++++++++++-- websockets/state/connection.js | 19 ++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 websockets/.env.example diff --git a/websockets/.env.example b/websockets/.env.example new file mode 100644 index 0000000..8f55cbd --- /dev/null +++ b/websockets/.env.example @@ -0,0 +1 @@ +PORT= \ No newline at end of file diff --git a/websockets/events/connection.js b/websockets/events/connection.js index 468d210..db4fe03 100644 --- a/websockets/events/connection.js +++ b/websockets/events/connection.js @@ -1,5 +1,46 @@ +import { addUser, removeUser } from "../state/connection"; + +const HEARTBEAT_INTERVAL = 30000; // 30 seconds +const HEARTBEAT_TIMEOUT = 10000; // 10 seconds + export const handleConnectionEvents = (io, socket) => { - socket.on("echo", (msg) => { - socket.emit("echo", msg); + let heartbeatInterval; + let heartbeatTimeout; + const startHeartbeat = () => { + heartbeatInterval = setInterval(() => { + socket.emit("heartbeat"); + + heartbeatTimeout = setTimeout(() => { + console.log( + `[Heartbeat] No response from ${socket.id}, disconnecting...` + ); + socket.disconnect(true); + }, HEARTBEAT_TIMEOUT); + }, HEARTBEAT_INTERVAL); + }; + + socket.on("heartbeat_ack", () => { + clearTimeout(heartbeatTimeout); + console.log(`[Heartbeat] Received pong from ${socket.id}`); + }); + + socket.on("join", (user) => { + addUser(socket, user); + console.log(`[Connection] User ${user.name} has joined the server`); + console.log(`[Connection] ${getUserCount()} users online`); + }); + + socket.on("leave", () => { + const user = removeUser(socket.id); + if (user) { + console.log(`[Connection] User ${user.name} has left the server`); + console.log(`[Connection] ${getUserCount()} users online`); + } + }); + + socket.on("disconnect", () => { + console.log("Connection Lost:", socket.id); + removeUser(socket.id); + console.log(`[Connection] ${getUserCount()} users online`); }); }; diff --git a/websockets/state/connection.js b/websockets/state/connection.js index e69de29..5f3b49b 100644 --- a/websockets/state/connection.js +++ b/websockets/state/connection.js @@ -0,0 +1,19 @@ +const users = new Map(); + +export const addUser = (socket, user) => { + users.set(socket.id, user); +}; + +export const removeUser = (socketID) => { + const userToDelete = { ...users.get(socketID) }; + users.delete(socketID); + return userToDelete; +}; + +export const getUser = (socketID) => { + return users.get(socketID); +}; + +export const getUserCount = () => { + return users.size; +}; -- 2.54.0