A connection event in Express is an event triggered when a client connects to the server, allowing the server to respond or log the connection.
Click to reveal answer
intermediate
How do you listen for connection events in an Express app?
You listen for connection events by attaching event listeners to the server object returned by app.listen(), for example using server.on('connection', callback).
Click to reveal answer
beginner
What object do you use to handle connection events in Express?
You use the HTTP server object returned by app.listen() to handle connection events, not the Express app object itself.
Click to reveal answer
intermediate
Why might you want to handle connection events in an Express app?
Handling connection events helps monitor active connections, log client activity, or manage resources like sockets for better server control.
Click to reveal answer
beginner
Show a simple example of handling a connection event in Express.
Hint: Use socket only inside connection callback [OK]
Common Mistakes:
Trying to use socket outside connection event
Confusing event names 'disconnect' vs 'disconnected'
Ignoring scope errors
5. You want to broadcast a message to all connected users except the one who just connected. Which code inside io.on('connection', (socket) => { ... }) correctly does this when a user connects?
hard
A. socket.on('message', 'A new user joined')
B. io.emit('message', 'A new user joined')
C. socket.emit('message', 'A new user joined')
D. socket.broadcast.emit('message', 'A new user joined')
Solution
Step 1: Understand broadcast
socket.broadcast.emit sends to all except the current socket.
Step 2: Compare options
io.emit sends to all including current socket; socket.emit sends only to current socket; socket.on listens, not sends.
Final Answer:
socket.broadcast.emit('message', 'A new user joined') -> Option D
Quick Check:
Broadcast excludes sender, perfect for this case [OK]
Hint: Use socket.broadcast.emit to exclude sender [OK]
Common Mistakes:
Using io.emit which sends to sender too
Using socket.emit which sends only to sender
Confusing emit with on
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.