Challenge - 5 Problems
Socket.io Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What does this Socket.io server code do?
Consider this Node.js Socket.io server snippet. What will happen when a client connects?
Node.js
import { Server } from 'socket.io'; const io = new Server(3000); io.on('connection', (socket) => { socket.emit('welcome', 'Hello client!'); });
Attempts:
2 left
💡 Hint
Look at the 'socket.emit' inside the 'connection' event.
✗ Incorrect
When a client connects, the server triggers the 'connection' event. Inside, it sends a 'welcome' message only to that client using socket.emit.
❓ state_output
intermediate2:00remaining
What is the output of this client-side Socket.io code?
Given this client code, what will be logged in the browser console?
Node.js
import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); socket.on('welcome', (msg) => { console.log(msg); });
Attempts:
2 left
💡 Hint
Check the event name and server URL in the code.
✗ Incorrect
The client listens for the 'welcome' event and logs the message sent by the server. The URL includes the port 3000, matching the server.
📝 Syntax
advanced2:00remaining
Which option correctly initializes a Socket.io server with CORS enabled?
You want to allow clients from any origin to connect. Which code snippet correctly sets up the server?
Attempts:
2 left
💡 Hint
Check the correct property name for CORS origin in Socket.io options.
✗ Incorrect
The correct way to enable CORS for all origins is to set cors: { origin: '*' }. Other options are invalid or incorrect property names.
🔧 Debug
advanced2:00remaining
Why does this Socket.io client fail to receive messages?
Client code:
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('message', (data) => {
console.log('Received:', data);
});
Server code:
import { Server } from 'socket.io';
const io = new Server(3000);
io.on('connection', (socket) => {
socket.emit('msg', 'Hello');
});
Why does the client never log 'Received: Hello'?
Attempts:
2 left
💡 Hint
Check the event names used on client and server.
✗ Incorrect
The client listens for 'message' events but the server emits 'msg'. Event names must match exactly for communication.
🧠 Conceptual
expert3:00remaining
What is the main advantage of using Socket.io over plain WebSockets?
Choose the best explanation for why developers prefer Socket.io instead of using raw WebSocket APIs.
Attempts:
2 left
💡 Hint
Think about features Socket.io adds beyond basic WebSocket communication.
✗ Incorrect
Socket.io provides extra features like automatic reconnection, fallback to other protocols if WebSocket is unavailable, and easy event-based communication. This simplifies building real-time apps.