WebSocket lets your server and browser talk instantly without waiting. It helps build real-time apps like chats or live updates.
Setting up WebSocket server in Express
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', (ws) => { ws.on('message', (message) => { // handle incoming message }); ws.send('Welcome!'); }); server.listen(3000);
Use http.createServer to create a server for both HTTP and WebSocket.
The WebSocket.Server listens on the same server to handle WebSocket connections.
const wss = new WebSocket.Server({ port: 8080 });wss.on('connection', (ws) => { ws.send('Hello client!'); });
ws.on('message', (msg) => { console.log('Received:', msg); });
This code sets up an Express server with a WebSocket server on the same port. When a client connects, it sends a welcome message. It also listens for messages from the client, logs them, and replies back with the same message.
const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); app.get('/', (req, res) => { res.send('WebSocket server is running'); }); wss.on('connection', (ws) => { ws.send('Welcome to WebSocket server!'); ws.on('message', (message) => { console.log('Received:', message); ws.send(`You said: ${message}`); }); }); server.listen(3000, () => { console.log('Server started on http://localhost:3000'); });
WebSocket connections stay open, unlike normal HTTP requests that close after response.
Always handle errors and client disconnects to keep your server stable.
WebSocket server lets your app send and receive messages instantly.
Use http.createServer with Express to share one server for HTTP and WebSocket.
Listen for 'connection' and 'message' events to interact with clients.
Practice
Solution
Step 1: Understand WebSocket functionality
WebSocket allows instant two-way communication between client and server, unlike HTTP which is one-way per request.Step 2: Identify Express role
Express is used to create the HTTP server, but WebSocket adds real-time messaging capability on top.Final Answer:
To enable real-time two-way communication between client and server -> Option AQuick Check:
WebSocket = real-time two-way communication [OK]
- Confusing WebSocket with static file serving
- Thinking WebSocket handles database queries
- Assuming WebSocket renders HTML
Solution
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.Step 2: Identify correct server creation method
http.createServer(app) creates an HTTP server that can be shared with WebSocket.Final Answer:
const server = http.createServer(app); -> Option AQuick Check:
Use http.createServer(app) for WebSocket [OK]
- Using express.createServer() which does not exist
- Creating WebSocket.Server with app directly
- Assigning express() to server without HTTP wrapper
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);Solution
Step 1: Understand event listeners setup
The server listens for 'connection' events, then for each connection listens for 'message' events.Step 2: Analyze message event handler
When a message arrives, it logs 'Received: ' plus the message content.Final Answer:
Received: Hello -> Option DQuick Check:
Message event logs 'Received: message' [OK]
- Expecting raw 'message' string without prefix
- Confusing event names or handlers
- Thinking ws.on is undefined
const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = http.createServer();
const wss = new WebSocket.Server({ server });
server.listen(3000);Solution
Step 1: Check module imports
The code uses http.createServer() but does not import the 'http' module, causing a ReferenceError.Step 2: Verify server creation and usage
http.createServer() requires the http module; without import, server is undefined.Final Answer:
http module is not imported -> Option BQuick Check:
Missing http import causes error [OK]
- Forgetting to import http module
- Passing express app directly to WebSocket.Server
- Calling listen before server creation
wss.on('connection', ws => {
ws.on('message', message => {
// Broadcast message to all clients
???
});
});Solution
Step 1: Identify how to access all clients
The WebSocket.Server instance 'wss' has a 'clients' set containing all connected clients.Step 2: Filter clients by open connection and send message
Only clients with readyState === WebSocket.OPEN can receive messages safely.Final Answer:
wss.clients.forEach(client => { if(client.readyState === WebSocket.OPEN) client.send(message); }); -> Option CQuick Check:
Broadcast uses wss.clients with readyState check [OK]
- Using ws.clients which does not exist
- Calling non-existent broadcast method
- Accessing server.clients which is undefined
Ready to prove it?
Pass the test and this pattern moves unknown
