Why Choose Server‑Sent Events Over WebSocket for Simple Real‑Time Push?
The article explains how Server‑Sent Events (SSE) provide a lightweight, one‑way server‑to‑client push mechanism that avoids the complexity of WebSocket or polling, shows its protocol details, compares it with WebSocket, and demonstrates integration with Spring MVC and the browser EventSource API.
1. SSE Push Technology
Server‑Sent Events (SSE) are part of the HTML5 specification and consist of a simple text‑based protocol where the server responds with the MIME type text/event-stream. Each event is a series of key‑value lines separated by a blank line ("\r\n"). The main keys are data (event payload, can appear multiple times), event (type of event), id (identifier for reconnection), and retry (reconnection delay).
SSE works only from server to client, making it lighter than full‑duplex WebSocket connections.
2. SSE vs WebSocket
SSE is one‑way (server → client) while WebSocket supports bidirectional communication.
SSE is more lightweight and easier to develop; it does not require protocol upgrades.
SSE natively supports automatic reconnection after a broken connection.
3. Using SSE in Spring MVC
Spring MVC provides built‑in support for SSE. To create an SSE endpoint you return an SseEmitter object from a controller method and set produces="text/event-stream". The emitter can be shared for broadcast or created per session for point‑to‑point messages. You can call send() on the emitter from another thread to push events and complete() to close the connection.
4. Browser‑Side EventSource
Because SSE is an HTML5 feature, the client creates an EventSource object with the URL of the SSE endpoint and registers listeners for message, error, or custom events. The API is simple and works in modern browsers; older browsers like IE need a polyfill.
Summary
SSE offers a lightweight alternative to long polling, Comet, and WebSocket for scenarios where the server needs to push small‑scale real‑time updates. Choose the technology that best fits the business requirements—there is no universally best solution, only the most suitable one.
Related code repository: https://gitee.com/felord/sse-push
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
