Performance: Emitting and receiving messages
This concept affects server response time and network latency impacting how fast messages are sent and received between client and server.
app.get('/send', (req, res) => { // Using setImmediate to batch emits asynchronously let i = 0; function emitBatch() { for(let count = 0; count < 100; count++, i++) { io.emit('message', { text: `Message ${i}` }); if(i >= 10000) return res.send('Messages sent'); } setImmediate(emitBatch); } emitBatch(); });
app.get('/send', (req, res) => { // Emitting message inside a heavy synchronous loop for(let i = 0; i < 10000; i++) { io.emit('message', { text: `Message ${i}` }); } res.send('Messages sent'); });
| Pattern | Event Loop Impact | Network Load | Client Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous heavy emits | Blocks event loop | High burst load | Delayed input response | [X] Bad |
| Asynchronous batched emits | Non-blocking event loop | Evenly distributed load | Fast input response | [OK] Good |
'chat message' with data 'Hello' to all clients using Socket.IO in Express?io.emit method sends a message to all connected clients.io.emit('chat message', 'Hello'); correctly emits the event with data.io.on('connection', (socket) => {
socket.on('greet', (msg) => {
socket.emit('reply', `Hello, ${msg}`);
});
});'greet' with message 'Alice'?io.on('connection', (socket) => {
socket.emit('welcome', 'Hello client');
socket.on('message', (msg) => {
io.emit('message', msg);
});
socket.on('disconnect', () => {
socket.emit('goodbye', 'Bye');
});
});targetId?io.to(socketId).emit() to send messages to a specific client.io.to(targetId).emit() to send only to the client with targetId.Pass the test and this pattern moves unknown