Suggest an editImprove this articleRefine the answer for “How does WebSocket work?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**WebSocket** is a network protocol that creates a persistent, two-way connection between a client (browser) and a server over a single TCP channel. **Key point:** unlike HTTP (request-response, the client always initiates), WebSocket is a persistent connection where both sides can send data at any moment.Shown above the full answer for quick recall.Answer (EN)Image## What WebSocket is > **WebSocket** is a network protocol that creates a **persistent, two-way connection** between a client (browser) and a server over a single TCP channel. Unlike HTTP: - HTTP is **request-response** (the client always initiates); - WebSocket is a **persistent connection**, where **both sides can send data at any moment**. ## The basic idea A regular HTTP request: ```javascript Client → Server: give me new data Server → Client: here is the data (connection closed) ``` WebSocket: ```javascript Client ↔ Server: connection established (once) From then on they communicate directly, without repeated requests ``` ## A simple example > Imagine you are talking to the server on the phone: > > - HTTP is like dialing the number again each time, saying one sentence, and hanging up. > - WebSocket is like calling once and talking for as long as you want, in both directions. ## How the connection is established (handshake) 1. The client opens a connection: ```javascript GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: <random-key> Sec-WebSocket-Version: 13 ``` 2. The server responds: ```javascript HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: <hash-key> ``` 3. After that, **the HTTP connection is "upgraded" to WebSocket**. It is no longer HTTP, but a **persistent, two-way channel** over TCP. ## What it looks like on the client (in the browser) ### Example: ```javascript // Create the connection const socket = new WebSocket('wss://example.com/chat'); // When the connection is established socket.addEventListener('open', () => { console.log('Connection open'); socket.send('Hello, server!'); }); // When messages arrive socket.addEventListener('message', (event) => { console.log('Message received:', event.data); }); // On error socket.addEventListener('error', (err) => { console.error('Error:', err); }); // When the connection closes socket.addEventListener('close', () => { console.log('Connection closed'); }); ``` The `ws://` or `wss://` prefix (similar to `http` and `https`): - `ws://` - unencrypted - `wss://` - a secure connection (over TLS) ## How the server works (in Node.js) An example with the `ws` library: ```javascript import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); ws.on('message', (msg) => { console.log('Received:', msg.toString()); ws.send(`You said: ${msg}`); }); ws.on('close', () => console.log('Client disconnected')); }); ``` Now any client can connect: ```javascript const socket = new WebSocket('ws://localhost:8080'); ``` ## What keeps a WebSocket "alive" A WebSocket stays open as long as: - the connection is not interrupted; - one of the sides does not call `.close()`; - a timeout or network error does not occur. The browser and server can **periodically send "pings"** (ping/pong) to check that the connection is alive. ## Message format WebSocket transmits data **in binary or text form**. On the client, `event.data` can be: - `string` - `Blob` - `ArrayBuffer` You can even send JSON: ```javascript socket.send(JSON.stringify({ type: 'chat', text: 'Hello!' })); ``` ## Why WebSocket is better than HTTP polling | Approach | What it does | Downsides | | --- | --- | --- | | **Polling** | the client makes a `fetch()` every X seconds | delays, extra requests | | **Long Polling** | the client keeps a request "open" until a response | high load on the server | | **WebSocket** | one persistent, two-way connection | harder to implement, needs a server with WS support | ## Support Works in all modern browsers (`Chrome`, `Firefox`, `Safari`, `Edge`, `Opera`, `Node.js`) and even in **cloud functions and Web Workers**. ## Where WebSocket is used - Chats and messengers (Telegram Web, Slack, Discord) - Trading terminals and exchanges (real time) - Online games - Live notifications (push events) - Collaborative document editing (Google Docs) - Real-time geolocation tracking ## Summary | What | Description | | --- | --- | | **Protocol type** | Two-way, on top of TCP | | **URL scheme** | `ws://` or `wss://` | | **Main difference from HTTP** | A persistent connection and the ability to send data from both sides | | **Support** | All modern browsers | | **Typical uses** | Chats, online games, notifications, exchanges | In summary: > WebSocket = a persistent, two-way, asynchronous communication channel between the browser and the server. > > It **keeps the connection open** and lets data be exchanged **in real time**, > without reloading the page and without constant HTTP requests.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.