Skip to content

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 port 8080, listens for connection, message, and close events, and broadcasts each received message to all currently connected clients.

  • Client (index.html): connects to ws://localhost:8080, displays the connection status, sends typed messages, and updates the list in real time when new messages arrive.

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.
flowchart LR Utente(["🚶 Utente"]) subgraph Sistema ["Real-Time Bulletin Board with WebSocket and Node.js"] U1(["Connect to ws://localhost:8080"]) U2(["Send a chat message"]) U3(["Receive broadcast messages and status notices"]) U1 --> U2 U1 --> U3 U2 -.-> U3 end Utente --> U1 classDef actor fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef usecase fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef system fill:#f8fafc,stroke:#64748b,stroke-width:2px,color:#0f172a; class Utente actor; class U1,U2,U3 usecase; class Sistema system;

Diagram created with Mermaid

  • 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.

sequenceDiagram actor UtenteA as Client A (Browser) participant Server as Node.js Server (ws:8080) actor UtenteB as Client B (Browser) UtenteA->>Server: Upgrade request + WebSocket connection Server-->>UtenteA: Connection open + system message UtenteB->>Server: Upgrade request + WebSocket connection Server-->>UtenteB: Connection open + system message UtenteA->>Server: Send message text (socket.send) Server->>Server: Format JSON with timestamp and iterate over wss.clients Server-->>UtenteA: Broadcast JSON message Server-->>UtenteB: Broadcast JSON message UtenteA->>Server: Close tab or lose connection (close) Server->>Server: Remove socket from wss.clients

Diagram created with Mermaid

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).

flowchart LR subgraph LocalClient ["Local Machine - Browser"] HTML["index.html (HTML, CSS, Client JS)"] WS["WebSocket Client ws://localhost:8080"] end subgraph LocalNode ["Local Machine - Node.js Runtime"] SRV["server.js (WebSocketServer on :8080)"] MOD["ws Module (node_modules/ws)"] end HTML --> WS WS <-->|"Persistent WS Connection"| SRV SRV --- MOD

Diagram created with Mermaid

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 the ws dependency

Operating steps

    • Prerequisite: Node.js is installed.
    • Create a folder for the lab, initialize the project, and install the ws package:
    Bash
    mkdir lab-websocket-node
    cd lab-websocket-node
    npm init -y
    npm install ws
  1. 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"
    }
    }
  2. 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.js file creates a WebSocket server in Node.js on port 8080 using the ws library and broadcasts received messages to all connected clients.

    Here’s how it works step by step:

    • import { WebSocketServer, WebSocket } from 'ws'; imports the class used to create the WebSocket server and the constants/types from the ws library.
    • const PORT = 8080; sets the port on which the server listens.
    • const wss = new WebSocketServer({ port: PORT }); starts the WebSocket server on port 8080 and 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 (connection)
    Section titled “3.2. Handling a new connection (connection)”

    Whenever a client (for example, a browser tab that opens index.html) connects to ws://localhost:8080, wss.on('connection', (socket, req) => { ... }) runs:

    • req.socket.remoteAddress retrieves the client’s address and wss.clients.size indicates how many clients are currently active.
    • socket.send(...) sends only to that client a JSON message with type: '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 (message)
    Section titled “3.3. Receiving and broadcasting messages (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;
    • text containing the message text;
    • timestamp containing the local time (en-US).
    • The for (const client of wss.clients) loop checks all connected clients and sends the payload only to those with client.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);
    }
    }
    });
    • 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);
    });
    });
  3. Opens 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 (<style> inside <head>)
    Section titled “4.2. Internal style sheet (<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>

    Creates the application’s minimal interface: a title, the #status box for connection state, the #messages container for incoming messages, and the #chat-form with 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:8080 through the native WebSocket API, and defines appendMessage() 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 on close, 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 (escapeHtml), and closing the document
    Section titled “4.6. Script — Form submission, sanitization (escapeHtml), and closing the document”

    Intercepts form submission to prevent a page reload, verifies that the text is non-empty and that the socket is in WebSocket.OPEN state, 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('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;');
    }
    </script>
    </body>
    </html>

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.clients and checking client.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.OPEN prevents 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.size increases by one for each tab).

    Correct: each tab runs new WebSocket(...) independently and creates its own socket object on the server.

Which client event fires when the server sends a new message through client.send(payload)?

  • submit
  • message

    Correct: on the client, socket.addEventListener('message', ...) receives event.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