Skip to main content

Realtime sockets

All live game, room, survey, admin-monitor, and simulation traffic goes through Socket.IO 4.

Registration​

server/src/socket/index.js exports setupSocketListeners(io, users), called from server/index.js after the Socket.IO server is created.

Handlers (same users Map / roomManager where applicable):

ModuleDomain
userSocket.jsUser identity / presence
adminSocket.jsLive admin monitoring & control
arithmeticSocket.jsArithmetic stress task
foragingSocket.jsForaging rounds / tokens / chat
surveySocket.jsSurvey-related socket events
roomSocket.jsRoom join/leave/lifecycle
simulationSocket.jsAdmin simulation runs
roomManager.jsIn-memory room + session token state

Connection-level logic in index.js also handles:

  • session-restore — restore or mint a session token
  • Heartbeat / disconnect cleanup
  • get-room-stats

Error wrapping​

server/src/utils/errorWrapper.js:

  • wrapHandler — async socket handlers
  • wrapSyncHandler — sync handlers
  • wrapSocketHandlers — batch helper

Socket modules must use these wrappers so errors are logged and clients get a controlled failure instead of an unhandled rejection.

Client connection​

client/src/context/SocketContext.js:

  • Connects with io() to window.location.origin (dev: Next rewrites; prod/test: Nginx /socket.io/)
  • Persists a session token (localStorage / sessionStorage) for reconnect
  • Exposes useSocketContext, useConnectionState, and heartbeat/reconnect behavior

Mental model​

In-memory game objects live in GameRegistry / roomManager; durable rows are written through services and Prisma when rounds or sessions complete.