feat: websocket init
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
PORT=
|
||||||
@@ -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) => {
|
export const handleConnectionEvents = (io, socket) => {
|
||||||
socket.on("echo", (msg) => {
|
let heartbeatInterval;
|
||||||
socket.emit("echo", msg);
|
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`);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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;
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user