A Brief Introduction to WebSocket

The beginning of an HTTP request is always marked by the establishment of a connection between client and server. This connection is alive throughout the lifecycle of the request produced by the client, meaning that the connection will be closed once the server processes the request and sends its appropriate response to the client.

If a new HTTP request comes later on, it will have to establish a new connection before creating the request and close the connection once the request gets processed. This is the typical working mechanism of the HTTP protocol.

WebSocket protocol is based on the concept of full duplex communication. Simply speaking, full duplex communication means information can flow in both ways at any given point in time. In WebSocket, the initial handshake between client and server is done using HTTP. It creates a connection between them that remains alive until we close it voluntarily.

Data can now flow smoothly between the client and the server using the socket connection. WebSocket brings the concept of event-based communication into use. Unlike HTTP which used polling as a mechanism for client-server communication, WebSocket uses the concept of emitting.

In WebSocket, a client emits on an event and the server listens to the same event. Once the server receives a message on that event, it can process the message and emit a message of its own. This works both ways, meaning both the client and the server can emit messages to an event at any given point in time. This results in bi-directional data transfer with low latency.

Due to these features, WebSockets are used in scenarios that require real-time data transfer and interactivity like notifications, chat applications, trading services, and many more.

The most commonly used library for socket programming is socket.io which is built on top of WebSocket protocol. It is very simple to use and contains several features like fallback to HTTP long-polling or automatic reconnection.

You can learn more about socket.io at: https://socket.io/docs/v4/