Bird
Raised Fist0
Expressframework~20 mins

Setting up WebSocket server in Express - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebSocket Server Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this WebSocket server code output when a client connects?

Consider this Express server setup with WebSocket. What message does the server send to the client upon connection?

Express
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const server = app.listen(3000);
const wss = new WebSocketServer({ server });

wss.on('connection', ws => {
  ws.send('Welcome client!');
});
AThe client receives 'Welcome client!' message immediately after connecting.
BThe server closes the connection immediately after client connects.
CThe server throws an error because WebSocketServer is not properly initialized.
DThe client receives no message until it sends one first.
Attempts:
2 left
💡 Hint

Look at the ws.send inside the connection event handler.

📝 Syntax
intermediate
2:00remaining
Which option correctly initializes a WebSocket server with Express?

Choose the correct way to create a WebSocket server that shares the same HTTP server as Express.

Aconst wss = new WebSocketServer({ server: app.listen(3000) });
Bconst wss = new WebSocketServer({ port: 3000 });
Cconst wss = new WebSocketServer({ expressApp: app });
Dconst wss = new WebSocketServer({ httpServer: app });
Attempts:
2 left
💡 Hint

The WebSocket server needs the actual HTTP server instance, not the Express app.

🔧 Debug
advanced
2:00remaining
Why does this WebSocket server code cause a runtime error?

Identify the cause of the error in this code snippet:

Express
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const wss = new WebSocketServer({ server: app });

wss.on('connection', ws => {
  ws.send('Hello');
});

app.listen(3000);
AThe WebSocketServer is missing the port number, so it cannot listen.
BThe ws.send method is called before the connection is established.
CThe 'connection' event is misspelled, so the handler never runs.
DThe WebSocketServer is given the Express app instead of the HTTP server, causing a type error.
Attempts:
2 left
💡 Hint

Check what server option expects in WebSocketServer constructor.

❓ state_output
advanced
2:00remaining
What is the value of 'count' after 3 clients connect to this WebSocket server?

Consider this code that counts connected clients:

Express
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const server = app.listen(3000);
const wss = new WebSocketServer({ server });

let count = 0;

wss.on('connection', ws => {
  count++;
  ws.on('close', () => {
    count--;
  });
});
A1
B0
C3
DCannot determine without client disconnections
Attempts:
2 left
💡 Hint

Each new connection increments count by 1.

🧠 Conceptual
expert
3:00remaining
Which option best explains why WebSocketServer needs the HTTP server instance from Express?

Why must the WebSocket server share the HTTP server instance created by Express?

ABecause WebSocketServer only works with HTTPS servers, and Express creates them automatically.
BBecause WebSocketServer upgrades HTTP connections to WebSocket using the same server, enabling both protocols on one port.
CBecause WebSocketServer requires Express middleware to function properly.
DBecause WebSocketServer cannot listen on any port by itself and needs Express to handle routing.
Attempts:
2 left
💡 Hint

Think about how WebSocket connections start as HTTP requests.

Practice

(1/5)
1. What is the main purpose of setting up a WebSocket server with Express?
easy
A. To enable real-time two-way communication between client and server
B. To serve static files like images and CSS
C. To handle database queries asynchronously
D. To render HTML templates on the server

Solution

  1. Step 1: Understand WebSocket functionality

    WebSocket allows instant two-way communication between client and server, unlike HTTP which is one-way per request.
  2. Step 2: Identify Express role

    Express is used to create the HTTP server, but WebSocket adds real-time messaging capability on top.
  3. Final Answer:

    To enable real-time two-way communication between client and server -> Option A
  4. Quick Check:

    WebSocket = real-time two-way communication [OK]
Hint: WebSocket means instant two-way chat between client and server [OK]
Common Mistakes:
  • Confusing WebSocket with static file serving
  • Thinking WebSocket handles database queries
  • Assuming WebSocket renders HTML
2. Which code snippet correctly creates an HTTP server to use with WebSocket in Express?
easy
A. const server = http.createServer(app);
B. const server = express();
C. const server = new WebSocket.Server(app);
D. const server = express.createServer();

Solution

  1. Step 1: Recognize Express app and HTTP server creation

    Express app is created by calling express(), but to use WebSocket, you need an HTTP server wrapping the app.
  2. Step 2: Identify correct server creation method

    http.createServer(app) creates an HTTP server that can be shared with WebSocket.
  3. Final Answer:

    const server = http.createServer(app); -> Option A
  4. Quick Check:

    Use http.createServer(app) for WebSocket [OK]
Hint: Use http.createServer(app) to share server with WebSocket [OK]
Common Mistakes:
  • Using express.createServer() which does not exist
  • Creating WebSocket.Server with app directly
  • Assigning express() to server without HTTP wrapper
3. Given this code snippet, what will be logged when a client sends the message 'Hello'?
const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received: ${message}`);
  });
});
server.listen(3000);
medium
A. No output
B. message
C. Error: ws.on is not a function
D. Received: Hello

Solution

  1. Step 1: Understand event listeners setup

    The server listens for 'connection' events, then for each connection listens for 'message' events.
  2. Step 2: Analyze message event handler

    When a message arrives, it logs 'Received: ' plus the message content.
  3. Final Answer:

    Received: Hello -> Option D
  4. Quick Check:

    Message event logs 'Received: message' [OK]
Hint: Message event logs 'Received: ' plus message text [OK]
Common Mistakes:
  • Expecting raw 'message' string without prefix
  • Confusing event names or handlers
  • Thinking ws.on is undefined
4. Identify the error in this WebSocket server setup code:
const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = http.createServer();
const wss = new WebSocket.Server({ server });
server.listen(3000);
medium
A. WebSocket.Server should not receive server option
B. http module is not imported
C. express() should be passed to WebSocket.Server
D. server.listen should be called before creating WebSocket.Server

Solution

  1. Step 1: Check module imports

    The code uses http.createServer() but does not import the 'http' module, causing a ReferenceError.
  2. Step 2: Verify server creation and usage

    http.createServer() requires the http module; without import, server is undefined.
  3. Final Answer:

    http module is not imported -> Option B
  4. Quick Check:

    Missing http import causes error [OK]
Hint: Always import http before using http.createServer() [OK]
Common Mistakes:
  • Forgetting to import http module
  • Passing express app directly to WebSocket.Server
  • Calling listen before server creation
5. You want to broadcast a message to all connected WebSocket clients when one client sends a message. Which code snippet correctly implements this inside the 'connection' event handler?
wss.on('connection', ws => {
  ws.on('message', message => {
    // Broadcast message to all clients
    ???
  });
});
hard
A. ws.clients.forEach(client => client.send(message));
B. wss.broadcast(message);
C. wss.clients.forEach(client => { if(client.readyState === WebSocket.OPEN) client.send(message); });
D. server.clients.forEach(client => client.send(message));

Solution

  1. Step 1: Identify how to access all clients

    The WebSocket.Server instance 'wss' has a 'clients' set containing all connected clients.
  2. Step 2: Filter clients by open connection and send message

    Only clients with readyState === WebSocket.OPEN can receive messages safely.
  3. Final Answer:

    wss.clients.forEach(client => { if(client.readyState === WebSocket.OPEN) client.send(message); }); -> Option C
  4. Quick Check:

    Broadcast uses wss.clients with readyState check [OK]
Hint: Use wss.clients and check readyState before sending [OK]
Common Mistakes:
  • Using ws.clients which does not exist
  • Calling non-existent broadcast method
  • Accessing server.clients which is undefined
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