Before understanding Long Polling, WebSockets, Server-Sent Events lets understand how the basic communication over the internet using HTTP request happens. HTTP is the most common method of data transfer in client server-based architecture.
This is how a regular HTTP request works –
- Whenever a client wants to visit a web page, it makes an HTTP request to a web server.
- The server calculates the response
- The server sends the response back to the client.
1. Long Polling
Polling technology allows the servers to push information to a client whenever the data is available instead of returning an empty response if no data is available(a.k.a Ajax Polling).
In long polling a client sends a request to the server and holds the connection open, thus allowing the server to respond whenever the data is ready. Once the data becomes available, a full response is sent to the client and the client then immediately re-request information from the server so that the server will almost always have an available waiting request.
HTTP Long Polling working
- A client sends a request for a webpage to a server using regular HTTP.
- If the response is available the server immediately sends it back but if data/response is not available the server holds the request until a data is available or a timeout has occurred.
- Once the client receives the requested webpage, it immediately sends another request to the server, re-starting the process.
- Each request has a timeout and the client has to reconnect if the connection is closed due to timeouts.
2. Server-Sent Events (SSE)
Server-Sent Events Working
- The server opens a connection between the client and the server.
- The server sends the data to the client whenever there’s new information available.
Application of SSE
- Live Twitter, Instagram news feed.
- Monitoring services like – Pingdom, uptime monitor, etc.
- News updates or alerts
- Live sports score or stock price chart.
WebSockets is a thin lightweight communication protocol that provides a full-duplex communication channel over a single TCP(transfer control protocol) connection. Just like HTTP protocol WebSockets too work at layer 5 of the OSI model and use layer 4 TCP, but they are different(HTTP is half-duplex).
WebSockets work at port number 443 and 80(in case of unsecured connection). The WebSocket protocol enables the communication between a web browser and a web server with low weight overheads, providing real-time data transfer from and to the server. This became possible by providing a standardized way for the server to send content to the browser without being asked by the client and allowing for messages to be passed back and forth while keeping the connection open.