Websocket
Introduction
HTTP and WebSocket Protocols
HTTP and WebSocket both are communications protocols used in client-server communication.
HTTP protocol
First, let's see how the HTTP protocol works. HTTP is a unidirectional protocol, which means HTTP requests can only be sent one way from the client to the server. When a client sends an HTTP request to the server, a connection between the client and the server will be established. The server will then send a response back to the client, so each request will associate with a corresponding response. After the response is sent, the connection will be closed, so every time the client wants to send a new HTTP request to the server, it will need to establish a new connection each time.
The HTTP protocol is a reliable way for the client to get and send data to the server, but what about the other way around, how can the servers notify changes to the connected clients, they can not send an HTTP request to the clients. That's why Websocket was created.
WebSocket Protocols
WebSocket, on the other hand, is a bidirectional, full-duplex protocol, which allows the servers to communicate with the clients very easily. Now, let's take a look at how Websocket works.
First, unlike HTTP, any URIs using WebSocket protocol will start with ws:// or wss://. When the clients want to connect to the server through WebSocket Protocol, they will make a handshaking process by sending an upgrade request to the server to switch protocols. The server, if accepted the handshaking, will then establish and open a persistent connection between it and the clients. Message exchange will take place in bidirectional mode until the connection is lost. The connection will be closed if anyone of them (client or server) dies or decides to close it.
When to use WebSocket
Since the connection will be kept alive and no need to re-establish every time fetching or sending data, WebSocket is suitable for applications that need real-time updates from the server or continuously send data from the clients (e.g. Trading Websites, Gaming Applications, Chat Applications, ...)
Note
WebSocket is not suitable for fetching old data or if you just need to fetch data only once. In these cases, HTTP protocol is more efficient and better.