Bird
Raised Fist0
Expressframework~20 mins

Handling connection events in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Connection Event Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a client connects to this Express server?
Consider this Express server code. What will be logged when a client connects to the server?
Express
const express = require('express');
const app = express();
const server = app.listen(3000, () => console.log('Server started'));

server.on('connection', (socket) => {
  console.log('New client connected');
});
AThe message 'Server started' is logged each time a client connects.
BThe message 'New client connected' is logged each time a client connects.
CNo message is logged when a client connects because 'connection' event is not supported.
DAn error is thrown because 'server.on' is not a valid method.
Attempts:
2 left
💡 Hint
The 'connection' event is emitted by the underlying HTTP server when a new TCP connection is made.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Express connection event handler
Which option correctly fixes the syntax error in this code snippet?
Express
const express = require('express');
const app = express();
const server = app.listen(3000);

server.on('connection' (socket) => {
  console.log('Client connected');
});
AReplace 'connection' with 'connect': server.on('connect' (socket) => {...})
BRemove the parentheses around socket: server.on('connection', socket => {...})
CAdd a comma after 'connection': server.on('connection', (socket) => {...})
DChange 'on' to 'addListener': server.addListener('connection' (socket) => {...})
Attempts:
2 left
💡 Hint
Check the syntax of the event listener function parameters.
🔧 Debug
advanced
2:00remaining
Why does this Express server not log connection events?
This code is intended to log when a client connects, but nothing is logged. What is the cause?
Express
const express = require('express');
const app = express();

app.on('connection', (socket) => {
  console.log('Client connected');
});

app.listen(3000);
A'app' is an Express application and does not emit 'connection' events; the server object does.
BThe 'connection' event is deprecated and no longer works in Express.
CThe 'listen' method must be called with a callback to enable events.
DThe 'connection' event only fires on HTTPS servers, not HTTP.
Attempts:
2 left
💡 Hint
Consider which object emits the 'connection' event in Node.js HTTP servers.
❓ state_output
advanced
2:00remaining
What is the value of 'activeConnections' after three clients connect and one disconnects?
This Express server tracks active connections. What is the value of 'activeConnections' after three clients connect and one disconnects?
Express
const express = require('express');
const app = express();
const server = app.listen(3000);

let activeConnections = 0;

server.on('connection', (socket) => {
  activeConnections++;
  socket.on('close', () => {
    activeConnections--;
  });
});

// Assume three clients connect, then one disconnects
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Each connection increments, each close decrements the counter.
🧠 Conceptual
expert
2:00remaining
Which event should you listen to for detecting when an HTTP request is fully received in Express?
You want to run code when the entire HTTP request body has been received by your Express server. Which event is the best to listen for?
A'connection' event on the server object
B'request' event on the server object
C'data' event on the request object
D'end' event on the request object
Attempts:
2 left
💡 Hint
Think about the event that signals the end of data streaming on a request.

Practice

(1/5)
1. What does io.on('connection', callback) do in an Express app using Socket.IO?
easy
A. Runs the callback when a user disconnects
B. Runs the callback when the server starts
C. Runs the callback when a new user connects to the server
D. Runs the callback when the server shuts down

Solution

  1. Step 1: Understand the event name 'connection'

    The 'connection' event triggers when a new client connects to the server.
  2. Step 2: Understand the role of the callback

    The callback runs code to handle the new connection, such as setting up listeners.
  3. Final Answer:

    Runs the callback when a new user connects to the server -> Option C
  4. Quick Check:

    io.on('connection') = new user connected [OK]
Hint: Remember 'connection' means user joined [OK]
Common Mistakes:
  • Confusing 'connection' with 'disconnect'
  • Thinking it runs on server start
  • Assuming it runs on server shutdown
2. Which of the following is the correct syntax to listen for a user disconnect event on a socket?
easy
A. io.on('disconnect', () => { /* code */ })
B. socket.on('disconnect', () => { /* code */ })
C. socket.emit('disconnect', () => { /* code */ })
D. io.emit('disconnect', () => { /* code */ })

Solution

  1. Step 1: Identify the object to listen on

    The disconnect event is listened on the individual socket, not the io server object.
  2. Step 2: Use the correct method and event name

    Use socket.on('disconnect', callback) to run code when that socket disconnects.
  3. Final Answer:

    socket.on('disconnect', () => { /* code */ }) -> Option B
  4. Quick Check:

    socket.on('disconnect') = user left [OK]
Hint: Listen on socket, not io, for disconnect [OK]
Common Mistakes:
  • Using io.on instead of socket.on for disconnect
  • Using emit instead of on to listen
  • Listening disconnect on wrong object
3. What will be logged when this code runs and a user connects then disconnects?
io.on('connection', (socket) => {
  console.log('User connected');
  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});
medium
A. User connected
User disconnected
B. User disconnected
User connected
C. User connected
D. User disconnected

Solution

  1. Step 1: When user connects

    The 'connection' event triggers, logging 'User connected'.
  2. Step 2: When user disconnects

    The socket's 'disconnect' event triggers, logging 'User disconnected'.
  3. Final Answer:

    User connected
    User disconnected
    -> Option A
  4. Quick Check:

    Connect then disconnect logs both messages [OK]
Hint: Connect logs first, disconnect logs second [OK]
Common Mistakes:
  • Assuming disconnect logs before connect
  • Missing that disconnect logs separately
  • Thinking only one message logs
4. Identify the error in this code snippet that tries to log when a user disconnects:
io.on('connection', (socket) => {
  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

socket.on('disconnect', () => {
  console.log('Another disconnect');
});
medium
A. The second socket.on('disconnect') is outside the connection handler and socket is undefined
B. The first socket.on('disconnect') should be io.on('disconnect')
C. The disconnect event should be 'disconnected' not 'disconnect'
D. The console.log statements are missing semicolons

Solution

  1. Step 1: Check where socket is defined

    Socket is only defined inside the connection callback, so outside it socket is undefined.
  2. Step 2: Identify the error

    The second socket.on('disconnect') is outside the connection handler, causing a runtime error.
  3. Final Answer:

    The second socket.on('disconnect') is outside the connection handler and socket is undefined -> Option A
  4. Quick Check:

    socket undefined outside connection callback causes error [OK]
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

  1. Step 1: Understand broadcast

    socket.broadcast.emit sends to all except the current socket.
  2. Step 2: Compare options

    io.emit sends to all including current socket; socket.emit sends only to current socket; socket.on listens, not sends.
  3. Final Answer:

    socket.broadcast.emit('message', 'A new user joined') -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard