WebSocket

WebSocket is a protocol that enables full duplex communication between computers with a single TCP connection.

Before WebSocket

Before this protocol, the most popular over-the-network communication protocol was HTTP, where the client will send a request and the server will return the response. This communication is initiated by the client only and the server responds as per the request.

On the other hand, server-sent events (Server push) were another way where based on some event at the server end client gets an event to act upon.

Note that in both options the communication is one-way, both parties are not sending or receiving simultaneously.

Why do we need WebSocket?

WebSocket enables bidirectional communication, but why do we need that?

  • With the HTTP approach, for each client, the server may need to use different TCP connections.
  • HTTP has a high overhead considering the headers sent and received with each request and response respectively.
  • The client should maintain the mapping of connections to keep track of responses from the server.

Here, the single TCP connection which enables traffic in both directions solves the problem which is what the WebSocket protocol does. WebSocket is a kind of replacement for bidirectional communication technologies which are based on HTTP.

WebSocket is designed to work over HTTP 80 and 443 ports. However, the design does not limit it to HTTP only.

How does it work?

WebSocket protocol has majorly two parts.

  • Handshake
  • Data transfer

Simply, the client and server do a handshake and if the handshake was successful the data transfer starts where both client and server can independently send the data. This data is sent in small units which we can refer to as “messages”. Each message is composed of one or more frames.

I tried minimal code to understand the WebSocket protocol. Feel free to try out and explore the same. Once you follow the instructions given in the readme file and run the application locally, you have to open it in a different window or tab to see that the messages you type in one tab or window automatically appear on all opened tabs or windows. Find a short video below for clarity.