Given this Express and Socket.io server setup, what will the server log when a client connects?
const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const app = express(); const server = http.createServer(app); const io = new Server(server); io.on('connection', (socket) => { console.log('A user connected'); socket.on('disconnect', () => { console.log('A user disconnected'); }); }); server.listen(3000);
Look at the event name inside io.on() and what it logs.
The connection event triggers when a client connects, so the server logs 'A user connected'.
Choose the correct way to integrate Socket.io with an Express app.
Socket.io needs the HTTP server, not just the Express app.
Socket.io must be attached to the HTTP server created from Express, not the Express app itself.
Consider this code snippet:
let count = 0;
io.on('connection', (socket) => {
count++;
socket.on('disconnect', () => {
count--;
});
});What is the value of count after 3 clients connect and then all disconnect?
Think about how count changes on connection and disconnection.
Each connection increments count by 1, and each disconnect decrements it by 1. After 3 connect and 3 disconnect events, count returns to 0.
Review this server code snippet:
io.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('Message:', msg);
});
});Clients send messages with socket.emit('msg', 'hello'). Why does the server not log the messages?
Check the event names used by client and server.
Event names must match exactly. The server listens for 'message' but clients emit 'msg', so the server never receives those events.
Choose the statement that best explains Socket.io's integration with Express for real-time features.
Think about how Socket.io works with the HTTP server Express uses.
Socket.io attaches to the HTTP server created from Express. It handles WebSocket connections and fallback transports on the same server and port as Express HTTP requests.