0
0
Expressframework~30 mins

Setting up WebSocket server in Express - Try It Yourself

Choose your learning style9 modes available
Setting up WebSocket server
📖 Scenario: You want to create a simple chat server that can send and receive messages instantly using WebSockets. This will allow multiple users to connect and chat in real time.
🎯 Goal: Build a basic WebSocket server using Express and the ws library that accepts client connections and can broadcast messages to all connected clients.
📋 What You'll Learn
Create an Express server
Integrate the ws WebSocket library
Set up a WebSocket server on top of the Express server
Broadcast messages received from one client to all connected clients
💡 Why This Matters
🌍 Real World
Real-time chat apps, live notifications, multiplayer games, and collaborative tools use WebSocket servers to instantly share data between users.
💼 Career
Understanding WebSocket setup with Express is valuable for backend developers building interactive web applications requiring live updates.
Progress0 / 4 steps
1
Create Express server
Write code to create an Express app and start a server listening on port 3000. Name the Express app app and the server server.
Express
Need a hint?

Use express() to create the app and app.listen(3000) to start the server.

2
Import and configure WebSocket server
Import the ws library and create a WebSocket server named wss using new WebSocket.Server with the existing server as the HTTP server.
Express
Need a hint?

Use require('ws') to import and pass { server } to the WebSocket.Server constructor.

3
Handle client connections and messages
Add an event listener on wss for the 'connection' event with a callback that receives a ws client. Inside, add a 'message' event listener on ws that receives message data.
Express
Need a hint?

Use wss.on('connection', callback) and inside it ws.on('message', callback).

4
Broadcast messages to all clients
Inside the 'message' event listener, add code to send the received message to every connected client using wss.clients.forEach. Only send if the client is open (client.readyState === WebSocket.OPEN).
Express
Need a hint?

Loop over wss.clients and send the message only to clients with readyState === WebSocket.OPEN.