Understanding Server‑Sent Events (SSE): Comparison, API Details, and Node.js Demo
This article explains Server‑Sent Events (SSE), compares it with polling and WebSocket, outlines its advantages and limitations, provides API usage examples, and offers a complete Node.js/Express demo with front‑end code to illustrate real‑time one‑way data push.
In daily development, server-to-client data push scenarios such as real‑time dashboards, unread messages, and chat often arise.
This article introduces Server‑Sent Events (SSE), compares three common push solutions—polling, WebSocket, and SSE—and discusses their advantages and disadvantages.
Polling is a pseudo‑push technique that repeatedly sends HTTP requests, consuming resources and limited by browser concurrent connections.
WebSocket provides full‑duplex communication over a new ws/wss protocol, offering powerful features but requiring server support and being heavier.
SSE is a lightweight, one‑way protocol built on HTTP/HTTPS, supported by most browsers (except IE) and easy to deploy on existing servers.
The article lists SSE API details, including var source = new EventSource(url); and the source.readyState constants (CONNECTING = 0, OPEN = 1, CLOSED = 2) with events open , message , and error .
A complete demo is provided: a static HTML page that creates an EventSource , handles incoming messages, and appends them to a list, and a Node.js Express server that sets the appropriate headers and streams JSON data every second.
Running the demo involves creating index.html and index.js , installing Express via npm i express , and starting the server with node index .
In summary, SSE is lighter than WebSocket and ideal for one‑way push scenarios such as dashboards or notifications, while WebSocket should be chosen for bidirectional communication like chat; polling is generally discouraged.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.