Broadcast Messages to All Connected Users
Now that the server can receive messages, we need to distribute them to other connected users.
Socket.IO provides multiple broadcasting methods.
The io.emit() method sends an event to all connected clients, including the sender.
The socket.broadcast.emit() method sends an event to all connected clients except the sender.
For our chat application, we will use io.emit() so the sender also receives the published message through the same event handler.
Broadcasting Methods
All connected clients
Includes the sender.
Current socket
Sends an event only to the socket represented by this object.
All except sender
Excludes the current socket.
export function registerChatEvents(io) {
io.on('connection', (socket) => {
socket.on('chat:send', (payload) => {
if (!validateChatMessage(payload)) {
socket.emit('chat:error', {
message: 'Invalid message payload'
});
return;
}
const chatMessage = {
username: payload.username.trim(),
message: payload.message.trim(),
timestamp: new Date().toISOString()
};
io.emit('chat:message', chatMessage);
});
});
}
function validateChatMessage(payload) {
return Boolean(
payload &&
typeof payload.username === 'string' &&
typeof payload.message === 'string' &&
payload.username.trim().length > 0 &&
payload.username.trim().length <= 30 &&
payload.message.trim().length > 0 &&
payload.message.trim().length <= 1000
);
}The server validates incoming data, creates a timestamped message object, and broadcasts it to all connected clients.
io.emit() broadcasts to every connected client in the namespace.
socket.broadcast.emit() excludes the current sender.
Server-generated timestamps provide consistent message metadata.