There are different ways like:
WebSocket, Server-Sent Events (SSE), Polling, WebRTC, Push Notifications, MQTT, Socket.IO
Polling
In the context of client-server communication, polling is like continually asking “do you have
any updates?” from the client side. For example, imagine you’re waiting for a friend to finish
a task. You keep asking “Are you done yet?” – that’s like polling.
Short Polling:
In short polling, the client sends a request to the server asking if there’s any new information.
The server immediately responds with the data if it’s available or says “no data” if it’s not.
The client waits for a short period before sending another request. It’s like asking your friend
“Are you done yet?” every 6 minutes.
Advantages:
- Simple to Implement: Short polling is simple and requires little work to set up. It doesn’t
require any special type of server-side technology. - Instantaneous Error Detection: If the server is down, the client will know almost
immediately when it tries to poll.
Disadvantages:
- High Network Overhead: Short polling can cause a lot of network traffic as the client
keeps polling the server at regular intervals. - Wasted Resources: Many of the requests might return empty responses (especially if
data updates are infrequent), wasting computational and network resources. - Not Real-Time: There is a delay between when the new data arrives at the server and
when the client receives it. This delay could be up to the polling interval.
Long Polling:
In long polling, the client asks the server if there’s any new information, but this time the
server does not immediately respond with “no data”. Instead, it waits until it has some data
or until a timeout occurs. Once the client receives a response, it immediately sends another
request. In our friend example, it’s like asking “Let me know when you’re done” and waiting
until your friend signals they’ve finished before asking again.
Advantages:
- Reduced Network Overhead: Compared to short polling, long polling reduces network traffic
as it waits for an update before responding. - Near Real-Time Updates: The client receives updates almost instantly after they arrive on the
server, because the server holds the request until it has new data to send.
Disadvantages:
- Complexity: Long polling is more complex to implement than short polling, requiring better
handling of timeouts and more server resources to keep connections open. - Resource Intensive: Keeping connections open can be resource-intensive for the server if
there are many clients. - Delayed Error Detection: If the server is down, the client might not know until a timeout occurs.
WebSocket:
WebSocket is a communication protocol that provides full-duplex communication between a
client and a server over a long-lived connection. It’s commonly used in applications that require
real-time data exchange, such as chat applications, real-time gaming, and live updates.
How WebSocket work:
- Opening Handshake: The process begins with the client sending a standard HTTP request to
the server, with an “Upgrade: WebSocket™ header. This header indicates that the client wishes to
establish a WebSocket connection. - Server Response: If the server supports the WebSocket protocol, it agrees to the upgrade and
responds with an “HTTP/1.1101 Switching Protocols” status code, along with an
“Upgrade: WebSocket™ header. This completes the opening handshake, and the initial HTTP
connection is upgraded to a WebSocket connection.
- Data Transfer: Once the connection is established, data can be sent back and forth between
the client and the server. This is different from the typical HTTP request/response paradigm;
with WebSocket, both the client and the server can send data at any time. The data is sent in
the form of WebSocket frames. - Pings and Pongs: The WebSocket protocol includes built-in “ping” and “pong” messages for
keeping the connection alive. The server can periodically send a “ping” to the client, who should
respond with a “pong”. This helps to ensure that the connection is still active, and that the client is still responsive. - Closing the Connection: Either the client or the server can choose to close the WebSocket
connection at any time. This is done by sending a “close” frame, which can include a status code
and a reason for closing. The other party can then respond with its own “close” frame, at which point the connection is officially closed. - Error Handling: If an error occurs at any point, such as a network failure or a protocol
violation, the WebSocket connection is closed immediately.
Key Differences (Long-Polling vs WebSocket):
- Bidirectional vs Unidirectional:
WebSocket’s provide a bidirectional communication channel between client and server,
meaning data can be sent in both directions independently.
Long polling is essentially unidirectional, with the client initiating all requests.
- Persistent Connection:
WebSocket’s establish a persistent connection between client and server that stays open
for as long as needed.
In contrast, long polling uses a series of requests and responses, which are essentially
separate HTTP connections.
- Efficiency:
WebSocket’s are generally more efficient for real-time updates, especially when updates
are frequent, because they avoid the overhead of establishing a new HTTP connection for
each update.
Long polling can be less efficient because it involves more network overhead and can tie
up server resources keeping connections open.
- Complexity:
WebSocket’s can be more complex to set up and may require specific server-side technology.
Long polling is easier to implement and uses traditional HTTP connections.
Server-Sent Events (SSE):
Server-Sent Events (SSE) is a standard that allows a web server to push updates to the client
whenever new information is available. This is particularly useful for applications that require
real-time data updates, such as live news updates, sports scores, or stock prices.
Here’s a detailed explanation of how SSE works:
- Client Request: The client (usually a web browser) makes an HTTP request to the server,
asking to subscribe to an event stream. This is done by setting the “Accept” header
to “text/event-stream”. - Server Response: The server responds with an HTTP status code of 200 and
a “Content-Type” header set to “text/event-stream”, From this point on, the server can
send events to the client at any time. - Data Transfer: The server sends updates in the form of events. Each event is a block of
text that is sent over the connection. An event can include an “id”, an “event” type, and “data”.
The “data” field contains the actual message content. - Event Handling: On the client side, an EventSource JavaScript object is used to handle
incoming events. The EventSource object has several event handlers that can be used to handle
different types of events, including “onopen’, “onmessage’, and “onerror”. - Reconnection: If the connection is lost, the client will automatically try to reconnect to the
server after a few seconds. The server can also suggest a reconnection time by including a “retry”
field in the response. - Closing the Connection: Either the client or the server can choose to close the connection at any time. The client can close the connection by calling the EventSource object’s “close” method. The server can close the connection by simply not sending any more events.