0
0
Expressframework~10 mins

Setting up WebSocket server in Express - Visual Walkthrough

Choose your learning style9 modes available
Concept Flow - Setting up WebSocket server
Start Express Server
Create HTTP Server
Attach WebSocket Server to HTTP Server
Listen for WebSocket Connections
On Connection: Handle Messages
Send/Receive Messages
Close Connection
Server Running
This flow shows how an Express server is started, then a WebSocket server is attached to it to handle real-time message exchange.
Execution Sample
Express
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';

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

wss.on('connection', ws => {
  ws.on('message', message => {
    ws.send(`Echo: ${message}`);
  });
});

server.listen(3000);
This code sets up an Express app, creates an HTTP server, attaches a WebSocket server, and echoes back any received messages.
Execution Table
StepActionEvaluationResult
1Import express, http, ws modulesModules loadedReady to use express, createServer, WebSocketServer
2Create express appapp = express()Express app instance created
3Create HTTP server with express appserver = createServer(app)HTTP server created wrapping express
4Create WebSocket server attached to HTTP serverwss = new WebSocketServer({ server })WebSocket server ready to accept connections
5Listen for 'connection' event on wsswss.on('connection', ...)Handler set for new WebSocket clients
6Client connects to WebSocket serverconnection event triggeredws object created for client
7Listen for 'message' event on wsws.on('message', ...)Handler set for incoming messages
8Client sends message 'Hello'message event triggeredServer receives 'Hello'
9Server sends back 'Echo: Hello'ws.send(...) calledClient receives echo message
10Server listens on port 3000server.listen(3000)Server ready to accept HTTP and WebSocket connections
11No more stepsN/AExecution complete, server running
💡 Server runs indefinitely, waiting for WebSocket connections and messages
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 6After Step 8Final
appundefinedexpress app instanceexpress app instanceexpress app instanceexpress app instanceexpress app instanceexpress app instance
serverundefinedundefinedHTTP server instanceHTTP server instanceHTTP server instanceHTTP server instanceHTTP server instance
wssundefinedundefinedundefinedWebSocketServer instanceWebSocketServer instanceWebSocketServer instanceWebSocketServer instance
wsundefinedundefinedundefinedundefinedWebSocket client connection objectWebSocket client connection objectWebSocket client connection object
messageundefinedundefinedundefinedundefinedundefined'Hello''Hello'
Key Moments - 3 Insights
Why do we create an HTTP server with express app before attaching WebSocket server?
Because WebSocketServer needs a raw HTTP server to attach to, not just the express app. See execution_table step 3 and 4 where HTTP server is created first, then WebSocket server attaches to it.
How does the server know when a client sends a message?
The server listens for the 'message' event on the WebSocket connection object (ws). This is shown in execution_table step 7 and 8 where ws.on('message') triggers when client sends data.
What happens if we don't call server.listen()?
The server won't start listening for any HTTP or WebSocket connections, so no clients can connect. This is shown in execution_table step 10 where server.listen(3000) starts the server.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'wss' after step 4?
AExpress app instance
Bundefined
CWebSocketServer instance attached to HTTP server
DHTTP server instance
💡 Hint
Check the 'wss' row in variable_tracker after step 4
At which step does the server receive a message from the client?
AStep 7
BStep 8
CStep 6
DStep 9
💡 Hint
Look at execution_table rows describing 'message event triggered' and 'Server receives'
If we skip creating the HTTP server and pass express app directly to WebSocketServer, what happens?
AError because WebSocketServer expects an HTTP server, not express app
BWebSocket server attaches and works fine
CExpress app automatically converts to HTTP server
DServer listens on default port 80
💡 Hint
Refer to key_moments about why HTTP server is needed before WebSocketServer
Concept Snapshot
1. Create express app with express().
2. Create HTTP server using createServer(app).
3. Attach WebSocketServer to HTTP server.
4. Listen for 'connection' events to handle clients.
5. On client message, respond or process.
6. Start server with server.listen(port).

WebSocketServer needs raw HTTP server, not just express app.
Full Transcript
This visual execution shows how to set up a WebSocket server using express. First, express app is created. Then an HTTP server is created wrapping the express app. Next, a WebSocketServer is attached to this HTTP server. The server listens for new WebSocket connections. When a client connects, the server listens for messages from that client. Upon receiving a message, the server sends back an echo message. Finally, the server listens on port 3000 for HTTP and WebSocket connections. Variables like app, server, wss, ws, and message change as the code runs. Key points include the need for an HTTP server before WebSocketServer, how message events trigger, and the importance of calling server.listen to start the server. The quizzes test understanding of variable states and event steps.