image.png

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.

1. Persistent connection and three way handshake

1.1 Persistent connection

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.

1.2 Three-way handshake

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.

  1. SYN → Client sends a SYN (synchronize) packet to the server to start a connection. It says, “Hey, I want to connect and my initial sequence number is X.”
  2. SYN-ACK → Server acknowledges the packet that is sent by the client and sends this acknowledgement back to the client. It says, “Hi client, got your SYN packet. Here is my sequence number Y. Let’s sync.”
  3. ACK → Client sends and ACK (acknowledgement) back to confirm. It says, “I received your SYN-ACK, Ready to communicate. Sending data packets.”

After this, the TCP connection is established and the data transfer begins.

1.3 HTTP Servers

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.

2. What are websockets

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

3. Websockets v/s HTTP in depth