How to Build a Real-Time Chat Application Using WebSockets

WebSockets enable full-duplex communication between a client and server, making them perfect for real-time chat apps. Unlike HTTP polling, WebSockets keep a persistent connection open, allowing instant message delivery. This tutorial walks through building a simple chat server using Node.js and a browser client.

You’ll need Node.js installed. We’ll use the ws library for the backend and vanilla JavaScript for the frontend. The goal: users connect, send messages, and see all messages broadcasted in real time.

Article illustration

Setting Up the WebSocket Server

Install Dependencies

Create a new project folder and run:

  • npm init -y
  • npm install ws

Write the Server

In server.js, create a WebSocket server that listens on port 8080. When a client connects, store the connection in a clients array. On receiving a message, broadcast it to every connected client except the sender (or to all, depending on your design).

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set();

wss.on('connection', (ws) => {
  clients.add(ws);
  ws.on('message', (message) => {
    // Broadcast to all clients
    clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
  ws.on('close', () => clients.delete(ws));
});

Creating the Client Interface

Build a simple HTML page with an input field, a send button, and a message list. Use JavaScript to connect to ws://localhost:8080.

HTML Structure

  • A <ul id="messages"> to display incoming messages.
  • An <input> and <button> for sending.

Client JavaScript

Connect to the WebSocket, listen for incoming messages, and append them to the list. When the user clicks send, send the input text through the WebSocket.

const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => {
  const li = document.createElement('li');
  li.textContent = event.data;
  document.getElementById('messages').appendChild(li);
};
document.getElementById('send').onclick = () => {
  const input = document.getElementById('input');
  ws.send(input.value);
  input.value = '';
};

Running and Testing

Start the server with node server.js. Open two browser tabs on your HTML page. Type a message in one tab; it appears instantly in the other. This demonstrates real-time chat functionality with minimal code.

Next Steps

Enhance your app by adding username support, message persistence (database), or broadcast only to selected rooms. Always handle server errors and reconnection logic for a robust experience.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *