
Websockets provide a way to establish a persistent, full-duplex communication channel over a single TCP connection between client (typically a web browser) and the server.
A persistent connection is when multiple requests can be sent altogether with only a single three way handshake i.e. a single TCP connection. Advantages of a persistent connection are less latency (no need to repeat the handshake), less cpu and network overhead and faster page loading (especially for many small files).
Another definition of a persistent connection is that it stays open meaning one can send data through it unless that connection isn’t explicitly closed.
A three-way handshake is a process that TCP uses to establish a reliable connection b/w client and server which ensures both sides are ready to send and receive data. There are 3 steps in a three-way handshake.
After this, the TCP connection is established and the data transfer begins.
The http protocol uses this TCP protocol every time a request is sent to get back a response. Consider this example, when you are trying to send 100 requests at t=0s, this three-way handshake is established 100 times, 1 each for every request sent. Now to establish this connection, time is required and when performing real-time data communication, doing this at every millisecond doesn’t make sense and HTTP servers fail to do this. For this purpose websockets are used.
Websockets are a communication protocol that provide full-duplex, bidirectional connection between a client (like web-browser) and a server over a single, long-lived TCP.
| Feature | Websocket |
|---|---|
| Type | Full-duplex (two-way) |
| Connection | Persistent (stays open) |
| Latency | Very low (no new handshake) |
| Protocol | ws:// or wss:// for secure |
| Applications | Real-time chat apps, live stock price updates, real-time gps tracking |