Emitting and receiving messages lets your server and clients talk to each other in real time. This helps build interactive apps like chat or live updates.
Emitting and receiving messages in Express
socket.emit(eventName, data) socket.on(eventName, callback)
socket.emit sends a message with a name and data.
socket.on listens for messages with that name.
socket.emit('chat message', 'Hello everyone!')
socket.on('chat message', (msg) => { console.log('New message:', msg) })
This Express server uses Socket.IO to handle real-time chat messages. When a client sends a 'chat message', the server logs it and sends it to all connected clients.
import express from 'express' import http from 'http' import { Server } from 'socket.io' const app = express() const server = http.createServer(app) const io = new Server(server) app.get('/', (req, res) => { res.sendFile(new URL('index.html', import.meta.url).pathname) }) io.on('connection', (socket) => { console.log('A user connected') socket.on('chat message', (msg) => { console.log('Message received:', msg) io.emit('chat message', msg) // send to all clients }) socket.on('disconnect', () => { console.log('User disconnected') }) }) server.listen(3000, () => { console.log('Server listening on http://localhost:3000') })
Make sure to include the Socket.IO client script in your HTML to connect and send/receive messages.
Use unique event names to avoid confusion between different message types.
Remember to handle client disconnects to keep your app stable.
Emitting sends messages; receiving listens for them.
This helps build live, interactive apps with Express and Socket.IO.
Use clear event names and handle connections carefully.
Practice
Solution
Step 1: Understand the meaning of emitting
Emitting means sending a message or event from the server to clients or vice versa.Step 2: Differentiate emitting from receiving
Receiving means listening for messages, not sending them.Final Answer:
Sending a message to connected clients -> Option DQuick Check:
Emitting = Sending message [OK]
- Confusing emitting with receiving
- Thinking emitting closes connections
- Mixing emitting with server start
'chat message' with data 'Hello' to all clients using Socket.IO in Express?Solution
Step 1: Identify the method to send to all clients
Theio.emitmethod sends a message to all connected clients.Step 2: Check the syntax correctness
io.emit('chat message', 'Hello');correctly emits the event with data.Final Answer:
io.emit('chat message', 'Hello'); -> Option BQuick Check:
Use io.emit to broadcast [OK]
- Using io.on instead of io.emit
- Omitting the data argument
- Using socket.emit to broadcast to all clients
io.on('connection', (socket) => {
socket.on('greet', (msg) => {
socket.emit('reply', `Hello, ${msg}`);
});
});What will the client receive if it emits
'greet' with message 'Alice'?Solution
Step 1: Understand the event flow
The server listens for 'greet' from the client, then emits 'reply' back to the same client.Step 2: Check the emitted message content
The message sent is `Hello, ${msg}`, so with 'Alice' it becomes 'Hello, Alice'.Final Answer:
A 'reply' event with message 'Hello, Alice' -> Option AQuick Check:
Reply event sends greeting with name [OK]
- Expecting broadcast to all clients
- Confusing event names 'greet' and 'reply'
- Thinking no message is sent back
io.on('connection', (socket) => {
socket.emit('welcome', 'Hello client');
socket.on('message', (msg) => {
io.emit('message', msg);
});
socket.on('disconnect', () => {
socket.emit('goodbye', 'Bye');
});
});Solution
Step 1: Analyze the 'disconnect' event usage
When a client disconnects, the socket is closed and cannot emit messages.Step 2: Identify the error
Trying to emit 'goodbye' after disconnect causes an error because socket is no longer connected.Final Answer:
Emitting 'goodbye' after disconnect causes error -> Option CQuick Check:
Cannot emit after disconnect [OK]
- Thinking io.emit is invalid inside handlers
- Expecting callback needed for emit
- Assuming no error on emitting after disconnect
targetId?Solution
Step 1: Understand how to target a specific client
Socket.IO usesio.to(socketId).emit()to send messages to a specific client.Step 2: Evaluate each option
io.to(targetId).emit('private message', msg); correctly usesio.to(targetId).emit()to send only to the client withtargetId.Final Answer:
io.to(targetId).emit('private message', msg); -> Option AQuick Check:
Use io.to(socketId).emit for private messages [OK]
- Using io.emit broadcasts to all clients
- socket.broadcast.emit sends to all except sender
- socket.emit sends only to sender, not target
Ready to prove it?
Pass the test and this pattern moves unknown
