WebSocket lets your server and browser talk instantly without waiting. It helps build real-time apps like chats or live updates.
0
0
Setting up WebSocket server in Express
Introduction
You want to build a chat app where messages appear instantly.
You need live notifications on a website without refreshing the page.
You want to show real-time data like stock prices or sports scores.
You want a game where players see each other's moves immediately.
Syntax
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.
Examples
This creates a WebSocket server that listens on port 8080 directly, without Express HTTP server.
Express
const wss = new WebSocket.Server({ port: 8080 });Sends a welcome message to each client when they connect.
Express
wss.on('connection', (ws) => { ws.send('Hello client!'); });
Logs any message received from a client.
Express
ws.on('message', (msg) => { console.log('Received:', msg); });
Sample Program
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.
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 }); 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'); });
OutputSuccess
Important Notes
WebSocket connections stay open, unlike normal HTTP requests that close after response.
Always handle errors and client disconnects to keep your server stable.
Summary
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.