WebSocket's bidirectionality
In short
WebSocket is a bidirectional protocol because both the client and the server can initiate sending data at any moment - with no repeated requests, no waiting, and no closing the connection.
1. How this compares to HTTP
| Property | HTTP | WebSocket |
|---|---|---|
| Who initiates the exchange | Only the client | Both client and server |
| How long the connection lives | Until the request finishes | Until closed manually |
| Data transfer | One-directional (request → response) | Two-directional (both can send messages) |
| Uses TCP | Yes | Yes |
| Suited for real time | No | Yes |
Example:
- HTTP: Client → request → server responds → connection closes.
- WebSocket: Client ↔ server: both can continuously send messages to each other at any time.
2. Why this is technically possible
WebSocket is built on top of a single TCP connection that:
- is established once (via an HTTP "upgrade");
- stays open;
- lets both sides send messages (frames) asynchronously.
Messages are sent as frames, small binary chunks:
- the client can send a
TextorBinaryframe; - the server can respond with its own frames;
- either side can send them at any moment, even simultaneously.
3. An example of a "live" exchange
Once the connection is established:
Client → "Hello, server!"
Server → "Hi, client!"
Client → "Sending coordinates {x:10,y:20}"
Server → "Coordinates received"
Server → "To everyone: a player moved"No new HTTP requests, just a two-way stream of messages. This makes WebSocket ideal for chats, games, trading platforms, notifications, and dashboards.
4. What happens under the hood
- The client makes a regular HTTP request with headers:
Upgrade: websocket
Connection: Upgrade- The server responds:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade- The connection "switches" from HTTP to WebSocket. It's no longer request-response, it's now a persistent, two-way TCP channel.
5. Visually
HTTP:
Client ----request----> Server
Client <----response--- Server
(connection closed)
WebSocket:
Client <===============> Server
(one connection, both can write and read)6. Why this matters
Without bidirectionality, it would be impossible to build:
- real-time notifications;
- chats and messengers;
- data streaming (e.g. exchange prices);
- online games;
- state updates without reloading the page.
7. To sum up
WebSocket is considered bidirectional because the server and client can each independently initiate sending data over a single persistent connection, staying connected until one of the sides closes it.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.