Video in progress
What is WebSocket, and how does it differ from a plain HTTP request-response?
WebSocket is a two-way, long-lived channel over a single TCP connection. With HTTP the client asks, the server answers, and that's the end of it. With WebSocket the server can also send a message on its own at any time.
📖 Answer
With plain HTTP the client always makes the first move. The server can't write "a new message arrived" on its own; it has to wait for the client to ask again.
A WebSocket connection is opened once and stays open. Over that channel:
- the client sends messages to the server;
- the server sends messages to the client, even if nobody asked;
- there are no fresh headers, cookies or TCP handshake for each message.
In practice you need it for chat, online games, stock quotes, collaborative editing (Google Docs style), anywhere latency must be low and the server has to "push".
One catch: WebSocket is stateful. Every open connection takes memory and a file descriptor on the server. For a plain CRUD API, WebSocket is unnecessary complexity; REST is enough there.
Sign up to mark studied questions and save your progress.