Create the Chat Event Handler
We will now separate chat event handling from the main server configuration.
Create src/events/chat.events.js.
This module receives the Socket.IO server instance and registers event listeners for each client.
The first event we will implement is chat:send.
Whenever a client emits this event, the server receives the message payload and broadcasts it to connected clients.
src/events/chat.events.js
export function registerChatEvents(io) {
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
socket.on('chat:send', (payload) => {
console.log('Received message:', payload);
});
socket.on('disconnect', (reason) => {
console.log('Client disconnected:', socket.id, reason);
});
});
}Creates a reusable event registration function. Each connected socket receives its own chat:send and disconnect event listeners.
Key Takeaways
Keep event handlers separate from server initialization.
Register client-specific listeners inside the connection callback.
Use descriptive event names.