1. Keep session alive with ping-pong. 2. Refreshed tests.

This commit is contained in:
AG
2025-10-16 10:48:11 +03:00
parent 6f64b1daca
commit 95684a34f7
27 changed files with 420 additions and 100 deletions

View File

@@ -4,6 +4,21 @@ import { sessions, SessionState, broadcastToSession, handleWebSocketMessage } fr
const router = express.Router();
router.post('/sessions', (req, res) => {
const sessionId = uuidv4();
sessions.set(sessionId, {
state: SessionState.SETUP,
topic: null,
description: null,
expectedResponses: 0,
submittedCount: 0,
responses: new Map(),
clients: new Map(),
finalResult: null,
});
res.status(201).json({ sessionId });
});
router.post('/sessions/:sessionId/responses', async (req, res) => {
const { sessionId } = req.params;
const { userId, wants, accepts, afraidToAsk } = req.body;

View File

@@ -130,6 +130,13 @@ export const createWebSocketServer = (server: any) => {
console.log(`Client connecting to session: ${sessionId}`);
// Set up a ping interval to keep the connection alive
const pingInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
}
}, 30000); // Send ping every 30 seconds
ws.on('message', async (message) => {
const parsedMessage = JSON.parse(message.toString());
const { type, clientId, payload } = parsedMessage;
@@ -151,6 +158,7 @@ export const createWebSocketServer = (server: any) => {
});
ws.on('close', () => {
clearInterval(pingInterval); // Clear the interval when the connection closes
let disconnectedClientId: string | null = null;
for (const [clientId, clientWs] of sessionData.clients.entries()) {
if (clientWs === ws) {
@@ -205,6 +213,13 @@ export const handleWebSocketMessage = async (ws: WebSocket, sessionId: string, p
console.log(`Client ${clientId} registered successfully for session ${sessionId}.`);
break;
case 'PING':
// Respond to client pings with a pong
if (ws.readyState === WebSocket.OPEN) {
ws.pong();
}
break;
case 'SETUP_SESSION':
if (sessionData.state === SessionState.SETUP) {
const { expectedResponses, topic, description } = payload;