This guide will help you understand what are websockets and how they are different from HTTP. Where you should use websockets.
Websockets and HTTP both are protocols used for communication between client and sever in a 2-tier architecture model. In order to understand Websockets let’s first understand what is HTTP and how HTTP works.
What is HTTP protocol ?
HTTP is unidirectional protocol where the response is generated by the sever whenever a client requests for it.
HTTP is connection-oriented protocol and every time a client sends HTTP request to the server, a TCP connection is created between the client and server. Once the request is fulfilled, the TCP connection gets terminated.
Every time a new request is created by the client, a separate connection is established between the client and the sever. So if there are 50 requests, 50 separate connections will be created.
Consider an example of a chat application where one end is server and one end is client. In this case, if we’re using HTTP protocol which we now know is unidirectional. So, in order to receive new message from other end, the client needs to keep asking the server for any response.
What are websockets ?
Unlike HTTP, websocket is a bidirectional protocol. It starts with ws:// or wss://.
It is a stateful protocol and the connection remains alive until closed by any side of the connection.
Therefore there is no need for the client to send request each time to get new message from the server. Whenever a new message is received, the pusher sends that message to the server and the client receives that message via a listener.
When to use websockets over HTTP ?
Websockets can be used in applications where real time update is necessary. Below are some examples where you can use websockets –
- Chat Applications
- Multiplayer Games
- IoT (Internet of things)
- Application with real time updates (Trading Platforms)