A two-way phone call between browser and server.
A WebSocket is a two-way connection between a browser and a server that stays open. Either side can send a message at any time, with no new request.
With HTTP, the browser must ask first, every time. A WebSocket removes that rule. After one handshake, the pipe stays open and both sides can talk freely.
ws:// (plain) or wss:// (encrypted with TLS). Always use wss:// on the real internet.Some products need fast, frequent, two-way messages. HTTP is too slow and heavy for them:
Press Next to see how a normal HTTP connection becomes a WebSocket.
const ws = new WebSocket("wss://chat.example.com/chat");
ws.onopen = () => ws.send(JSON.stringify({ type: "hello", user: "asha" }));
ws.onmessage = (e) => show(JSON.parse(e.data));
ws.onclose = () => reconnectWithBackoff(); // YOU must write this
ws.onerror = (e) => console.log("socket error", e);A WebSocket server remembers its connections. If Asha is connected to Server A and Ravi to Server B, Server A cannot reach Ravi directly. The common answer (general idea):
| Term | Meaning in easy words |
|---|---|
| WebSocket | A two-way connection that stays open between client and server |
| Handshake | The HTTP request and 101 reply that start the WebSocket |
| Upgrade header | Tells the server the client wants to switch protocol |
| 101 Switching Protocols | The server's yes to the upgrade |
| ws:// and wss:// | Plain and TLS-encrypted WebSocket URLs |
| Frame | One piece of a WebSocket message |
| Ping / Pong | Small heartbeat messages to check the connection is alive |
| Sticky session | Sending a user to the same server every time |
| Fan-out | Delivering one message to many connected users |
| Backpressure | A slow reader that cannot keep up with a fast sender |
| Subprotocol | An agreed message format on top of WebSocket (for example STOMP) |
| Long polling | SSE | WebSockets | |
|---|---|---|---|
| Direction | Server to client | Server to client | Both ways |
| Data | Anything over HTTP | Text | Text + binary |
| Reconnect | DIY | Built in | DIY |
| Overhead per message | High | Low | Lowest |
| Scales how | Many held requests | Many held responses | Stateful connections + pub/sub |
| Best for | Fallback | One-way feeds | Chat, games, collaboration |