Chat with Web Sockets
Here is a practical, complete exercise
for creating a real-time mini chat / bulletin board
with WebSocket and Node.js,
using the lightweight ws library and a native HTML/JavaScript page (without additional frameworks).
Unlike a classic HTTP request (where the client asks and the server responds once), a WebSocket opens a persistent, bidirectional connection: both the server and connected clients can send messages at any time.
Exercise architecture
-
Server (
server.js): starts a WebSocket server on port8080, listens forconnection,message, andcloseevents, and broadcasts each received message to all currently connected clients. -
Client (
index.html): connects tows://localhost:8080, displays the connection status, sends typed messages, and updates the list in real time when new messages arrive.
Introduction
Section titled “Introduction”Use Case Diagram
Section titled “Use Case Diagram”The use case diagram describes the exercise workflow:
- the user opens the client and establishes a WebSocket connection with the Node.js server;
- they can then send text messages in real time and receive messages sent by other connected clients or view connection and disconnection status notices.
Diagram created with Mermaid
Sequence Diagram
Section titled “Sequence Diagram”-
Purpose: It illustrates the chronological order of events during the WebSocket connection, broadcast message delivery, and connection closure.
-
Reading note: Time flows vertically from top to bottom.
Diagram created with Mermaid
Deployment Diagram
Section titled “Deployment Diagram”Let’s see where the components run during the local exercise: the server runs in a Node.js process listening on ws://localhost:8080, while index.html is opened in the browser (for example, through Live Server in Visual Studio Code).
Diagram created with Mermaid
Project file structure
Section titled “ Project file structure”Before writing the code, initialize the project in the working folder with npm init -y, install ws (npm install ws), and make sure "type": "module" appears once in package.json:
Directorylab-websocket-node/
- server.js Node.js WebSocket server (port
8080) that broadcasts to connected clients - index.html HTML/CSS/JS client interface for sending and receiving real-time messages
- package.json Node.js project configuration with
"type": "module"and thewsdependency
- server.js Node.js WebSocket server (port
Implementation
Section titled “Implementation”Operating steps
-
Initialize the project and install ws:
Section titled “Initialize the project and install ws:”- Prerequisite: Node.js is installed.
- Create a folder for the lab, initialize the project, and install the ws package:
Bash mkdir lab-websocket-nodecd lab-websocket-nodenpm init -ynpm install ws -
Modify package.json
Section titled “Modify package.json”Open the package.json file in the project folder and make the following changes:
package.json {"name": "lab-websocket-node","version": "1.0.0","description": "Real-time chat exercise with WebSocket and Node.js","main": "server.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"type": "commonjs","type": "module","scripts": {"start": "node server.js","test": "echo \"Error: no test specified\" && exit 1""dependencies": {"ws": "^8.0.0"}} -
Write the WebSocket server (server.js):
Section titled “Write the WebSocket server (server.js):”Create the server.js file with the following code.
Every new client is added to wss.clients, allowing the server to send messages to all active users.
The
server.jsfile creates a WebSocket server in Node.js on port8080using thewslibrary and broadcasts received messages to all connected clients.Here’s how it works step by step:
3.1. Importing and starting the server
Section titled “3.1. Importing and starting the server”import { WebSocketServer, WebSocket } from 'ws';imports the class used to create the WebSocket server and the constants/types from thewslibrary.const PORT = 8080;sets the port on which the server listens.const wss = new WebSocketServer({ port: PORT });starts the WebSocket server on port8080and prints a confirmation message to the console.
server.js import { WebSocketServer, WebSocket } from 'ws';const PORT = 8080;const wss = new WebSocketServer({ port: PORT });console.log(`WebSocket server listening on ws://localhost:${PORT}`);3.2. Handling a new connection (
Section titled “3.2. Handling a new connection (connection)”connection)Whenever a client (for example, a browser tab that opens
index.html) connects tows://localhost:8080,wss.on('connection', (socket, req) => { ... })runs:req.socket.remoteAddressretrieves the client’s address andwss.clients.sizeindicates how many clients are currently active.socket.send(...)sends only to that client a JSON message withtype: 'system'confirming that the connection is active.
server.js /* ... */wss.on('connection', (socket, req) => {const clientIp = req.socket.remoteAddress;console.log(`New client connected (${clientIp}). Active clients: ${wss.clients.size}`);socket.send(JSON.stringify({type: 'system',text: 'WebSocket connection established with the server.'}));3.3. Receiving and broadcasting messages (
Section titled “3.3. Receiving and broadcasting messages (message)”message)When a client sends data,
socket.on('message', (rawData) => { ... })is triggered:rawData.toString().trim()converts the received data into text and removes extra whitespace; an empty message (!messageText) is ignored.- A JSON object (
payload) is built with: type: 'chat'to distinguish it from system messages;textcontaining the message text;timestampcontaining the local time (en-US).- The
for (const client of wss.clients)loop checks all connected clients and sends thepayloadonly to those withclient.readyState === WebSocket.OPEN(an actually open connection).
server.js /* ... */socket.on('message', (rawData) => {const messageText = rawData.toString().trim();if (!messageText) return;console.log(`Message received: ${messageText}`);const payload = JSON.stringify({type: 'chat',text: messageText,timestamp: new Date().toLocaleTimeString('en-US')});for (const client of wss.clients) {if (client.readyState === WebSocket.OPEN) {client.send(payload);}}});3.4. Closure and errors (
Section titled “3.4. Closure and errors (close and error)”closeanderror)socket.on('close', ...)runs when a client closes the tab or loses its connection and updates the console with the number of active clients.socket.on('error', ...)catches errors on an individual socket so a connection problem does not block the server.
server.js /* ... */socket.on('close', () => {console.log(`Client disconnected. Active clients: ${wss.clients.size}`);});socket.on('error', (err) => {console.error('Socket error:', err.message);});}); -
Create the HTML/JS client (index.html):
Section titled “Create the HTML/JS client (index.html):”4.1. Header (
Section titled “4.1. Header (<head>) and metadata”<head>) and metadataOpens the HTML5 document in English, sets UTF-8 encoding, adapts the scale to mobile devices through the viewport, and defines the browser tab title.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Lab WebSocket con Node.js</title></head>4.2. Internal style sheet (
Section titled “4.2. Internal style sheet (<style> inside <head>)”<style>inside<head>)Defines the centered bulletin board layout, scrollable message area (
#messages), visual distinction between chat messages (.msg) and system notices (.sys), and the disabled send-button state.<style>body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }#status { font-weight: 600; margin-bottom: 1rem; }#messages { border: 1px solid #cbd5e1; border-radius: 8px; padding: 1rem; height: 280px; overflow-y: auto; margin-bottom: 1rem; background: #f8fafc; }.msg { margin-bottom: 0.5rem; padding: 0.4rem 0.6rem; border-radius: 6px; background: #ffffff; border: 1px solid #e2e8f0; }.sys { color: #475569; font-style: italic; background: #f1f5f9; }form { display: flex; gap: 0.5rem; }input { flex: 1; padding: 0.6rem; border: 1px solid #94a3b8; border-radius: 6px; }button { padding: 0.6rem 1rem; border: none; border-radius: 6px; background: #2563eb; color: #fff; cursor: pointer; }button:disabled { background: #94a3b8; cursor: not-allowed; }</style></head>4.3. Page structure (
Section titled “4.3. Page structure (<body>)”<body>)Creates the application’s minimal interface: a title, the
#statusbox for connection state, the#messagescontainer for incoming messages, and the#chat-formwith a text field and Send button (initially disabled until the WebSocket connects).<body><h1>Real-Time Bulletin Board (WebSocket)</h1><div id="status">Status: connecting...</div><div id="messages"></div><form id="chat-form"><input id="msg-input" type="text" placeholder="Write a message..." autocomplete="off" required /><button id="send-btn" type="submit" disabled>Send</button></form>4.4. Script — DOM references, WebSocket connection, and rendering function
Section titled “4.4. Script — DOM references, WebSocket connection, and rendering function”Retrieves the page’s key elements, opens the connection to
ws://localhost:8080through the native WebSocket API, and definesappendMessage()to add an element to the container and automatically scroll the chat downward.<script>const statusEl = document.getElementById('status');const messagesEl = document.getElementById('messages');const formEl = document.getElementById('chat-form');const inputEl = document.getElementById('msg-input');const sendBtn = document.getElementById('send-btn');const socket = new WebSocket('ws://localhost:8080');function appendMessage(htmlContent, isSystem = false) {const div = document.createElement('div');div.className = isSystem ? 'msg sys' : 'msg';div.innerHTML = htmlContent;messagesEl.appendChild(div);messagesEl.scrollTop = messagesEl.scrollHeight;}4.5. Script — Handling socket events (open, message, close, error)
Section titled “4.5. Script — Handling socket events (open, message, close, error)”Reacts to WebSocket channel changes: enables the button on
open, decodes the JSON received from the server and displays it (message), disables sending onclose, and reports connection anomalies (error).socket.addEventListener('open', () => {statusEl.textContent = 'Status: connected to ws://localhost:8080';sendBtn.disabled = false;});socket.addEventListener('message', (event) => {const data = JSON.parse(event.data);if (data.type === 'system') {appendMessage(data.text, true);return;}appendMessage(`<strong>[${data.timestamp}]</strong> ${escapeHtml(data.text)}`);});socket.addEventListener('close', () => {statusEl.textContent = 'Status: disconnected from server';sendBtn.disabled = true;});socket.addEventListener('error', () => {statusEl.textContent = 'Status: connection error';});4.6. Script — Form submission, sanitization (
Section titled “4.6. Script — Form submission, sanitization (escapeHtml), and closing the document”escapeHtml), and closing the documentIntercepts form submission to prevent a page reload, verifies that the text is non-empty and that the socket is in
WebSocket.OPENstate, sends the message, and clears the input.escapeHtml()neutralizes special characters before inserting text into HTML; the script and body elements are then closed.formEl.addEventListener('submit', (event) => {event.preventDefault();const text = inputEl.value.trim();if (!text || socket.readyState !== WebSocket.OPEN) return;socket.send(text);inputEl.value = '';inputEl.focus();});function escapeHtml(str) {return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');}</script></body></html>
Testing the code
Section titled “Testing the code”Summary
Section titled “Summary”Learning Check
Section titled “Learning Check”The answers to the quizzes on this page are saved in your browser's local storage and remain stored between visits
What is a key difference between a classic HTTP request and a WebSocket connection?
- WebSocket cannot send messages from the server to the client.
- WebSocket maintains a persistent, bidirectional connection between client and server.
Correct: once the connection is open, both the server and connected clients can send messages at any time without opening a new request each time.
- WebSocket only works without JavaScript in the browser.
In the Node.js server code, what is the purpose of the wss.clients set?
- To permanently save messages in a database.
- To automatically convert HTML into CSS.
- To track currently connected clients and broadcast messages to them.
Correct: by iterating over
wss.clientsand checkingclient.readyState === WebSocket.OPEN, the server can forward the message to all active clients.
Why does the client check socket.readyState === WebSocket.OPEN before calling socket.send(text)?
- To avoid sending data while the connection is not yet open or is already closed.
- To automatically encrypt the message text.
- To ensure that the WebSocket channel is ready to transmit messages.
Correct: checking
WebSocket.OPENprevents errors or empty sends while the socket is still connecting (CONNECTING) or already closed (CLOSED).
If you open index.html in two separate browser tabs connected to ws://localhost:8080, how does the server treat them?
- As a single shared connection that overwrites messages.
- As two distinct WebSocket connections (
wss.clients.sizeincreases by one for each tab).Correct: each tab runs
new WebSocket(...)independently and creates its ownsocketobject on the server.
Which client event fires when the server sends a new message through client.send(payload)?
-
submit -
messageCorrect: on the client,
socket.addEventListener('message', ...)receivesevent.data, which contains the payload sent by the server.
What is the purpose of escapeHtml(str) before inserting message text into the page?
- To format the time using the Italian time zone.
- To neutralize special HTML characters (such as
<and>) so they are not interpreted as tags or scripts.Correct: escaping special characters reduces the risk of HTML/XSS injection when inserting text supplied by users.
Quiz progress
0 / 0 questions answered (0%)
0 correct answers
Your score
0%
0 / 0 correct answers
Answered: 0 / 0 (0%)
STICS © 2026 by Carlo Scocco is licensed under CC BY-NC 4.0