Server-to-Client Data Push: Comparing Polling, WebSocket, and SSE with Implementation Guide
This article explains the three main server‑to‑client push techniques—polling, WebSocket, and Server‑Sent Events—detailing their advantages, drawbacks, browser compatibility, and provides step‑by‑step Node.js and front‑end demos for implementing SSE in real‑time applications.
Implementation Scenarios for Server-to-Client Data Push
In many web applications, the server needs to actively push data to the client, such as real‑time dashboards, unread messages, or chat.
Common Solutions
Polling
WebSocket
SSE
Polling Overview
Polling repeatedly sends HTTP requests from the client, creating unnecessary overhead, consuming connections, and providing a pseudo‑push experience.
Drawbacks include repeated handshakes, constant client processing, limited concurrent connections, and latency.
WebSocket Overview
WebSocket provides full‑duplex communication, allowing bidirectional messages, but requires support for the ws/wss protocol and is heavier.
SSE Overview
Server‑Sent Events (SSE) is a unidirectional, lightweight HTTP‑based protocol for server‑to‑client pushes, with automatic reconnection and low client overhead, but not supported by IE.
Differences Between WebSocket and SSE
WebSocket is full‑duplex and requires a separate protocol; SSE is one‑way, built on HTTP, lighter, and easier to deploy.
SSE API
Creating a connection: var source = new EventSource(url);
Connection State
source.readyState returns 0 (CONNECTING), 1 (OPEN), or 2 (CLOSED).
Events
open – triggered when the connection opens
message – triggered on incoming data
error – triggered on communication errors
Data Format
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-aliveDemo
Front‑end HTML/JS demo and back‑end Node.js Express server that streams JSON messages every second.
Conclusion
SSE is lighter than WebSocket and works over HTTP.
Use SSE for one‑way push scenarios (dashboards, notifications).
Use WebSocket for bidirectional communication (chat).
Polling should be avoided except for compatibility edge cases.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.