WebSockets in JavaScript: Building Real-Time Applications from Scratch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

WebSockets in JavaScript: When a "Live" Site Is Not Magic, But Code

\n\n

Have you ever wondered how online chats, real-time stock quotes, or multiplayer browser games work? The secret is simple and elegant — WebSockets in JavaScript. This technology turns a static website into a living organism that instantly reacts to the actions of other users.

\n\n

In this article, we won't just cover the theory. We'll write a real chat from scratch, learn how to handle errors, and understand why real-time applications on WebSockets work faster than the good old AJAX with polling. Buckle up — it's going to be interesting.

\n\n

Why HTTP Is Not Suitable for Real-Time? (A Quick Primer)

\n\n

Regular HTTP works on a "request-response" principle. The client asks — the server answers. If the server wants to say something on its own (e.g., "a new message has arrived"), it has to wait until the client asks again. This is reminiscent of communicating by carrier pigeons — slow and inefficient.

\n\n

Developers have come up with workarounds:

\n
    \n
  • Polling — the client pings the server every 5 seconds: "So, any news?"
  • \n
  • Long polling — the server keeps the connection open until a response is available (but it's still a one-way channel).
  • \n
\n\n

And then WebSockets enter the scene. Imagine you've opened a telephone line between the browser and the server. Both can speak at any time, simultaneously, without delays for "picking up the receiver." That's the magic of the JavaScript WebSocket API.

\n\n

How WebSocket Works: Protocol, Handshake, Messages

\n\n

Technically, WebSocket is a separate protocol (ws:// or wss:// for encrypted connections). It all starts with an HTTP handshake:

\n\n
    \n
  1. The client sends a regular HTTP request with the header Upgrade: websocket.
  2. \n
  3. The server responds: "101 Switching Protocols" — and the connection is "upgraded" to WebSocket.
  4. \n
  5. After that — full duplex: data flies in both directions in the form of frames (text or binary data).
  6. \n
\n\n

In the browser, the built-in WebSocket object is used to work with WebSocket. No additional libraries are needed — pure JavaScript WebSocket works out of the box in all modern browsers.

\n\n

Writing Your First Real-Time Chat in JavaScript

\n\n

Let's create a simple chat. We'll write the server part using Node.js with the ws library (the most popular for WebSocket Node.js), and the client in pure JavaScript.

\n\n

Step 1. Server Setup

\n\n
npm init -y\nnpm install ws
\n\n

Step 2. Server Code (server.js)

\n\n
const WebSocket = require('ws');\n\nconst wss = new WebSocket.Server({ port: 8080 });\n\nwss.on('connection', function connection(ws) {\n    console.log('New user connected');\n\n    // Send a welcome message to the new client\n    ws.send(JSON.stringify({\n        type: 'system',\n        message: 'Welcome to the chat!'\n    }));\n\n    // Receive messages from the client\n    ws.on('message', function incoming(data) {\n        const message = JSON.parse(data);\n        console.log('Received:', message);\n\n        // Broadcast the message to all connected clients\n        wss.clients.forEach(function each(client) {\n            if (client.readyState === WebSocket.OPEN) {\n                client.send(JSON.stringify({\n                    type: 'message',\n                    user: message.user,\n                    text: message.text,\n                    time: new Date().toLocaleTimeString()\n                }));\n            }\n        });\n    });\n\n    // Handle disconnection\n    ws.on('close', function() {\n        console.log('User disconnected');\n    });\n});\n\nconsole.log('Server running on ws://localhost:8080');
\n\n

Step 3. Clie

Blogs

Book Recommendations