feat: websocket init
This commit is contained in:
@@ -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`);
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user