HTML SSE (Server-Sent Events)
Subject: html
π HTML Server-Sent Events (SSE)
Server-Sent Events (SSE) allow a server to push real-time updates to the browser over a single, long-lived HTTP connection. This is part of the HTML5 specification.
Useful for:
- β News tickers
- β Live notifications
- β Real-time dashboards
- β Stock/weather updates
- β Social media feeds
π‘ How SSE Works
- The browser creates a connection using the
EventSource
API - The server keeps the connection open and pushes data as needed
- Data is sent in
text/event-stream
format - One-way only (server β client)
π‘ When to Use SSE
Use SSE when:
- Only the server needs to send updates
- You want simplicity over full-duplex (like WebSockets)
- Youβre building real-time UIs that listen for backend events
π§± Basic Client-Side Syntax
π HTML + JavaScript Example
π Server Response Format
The server script (server.php
) should return content in this format:
π§ Important HTTP Headers
Header | Purpose |
---|---|
Content-Type | Must be text/event-stream |
Cache-Control | Use no-cache to prevent caching |
Connection | Use keep-alive to maintain open connection |
β Advantages of SSE
- Simpler than WebSockets for server-to-client only
- Built-in reconnect and retry mechanism
- Lightweight: no polling needed
- Text-based (easy to debug and test)
β οΈ Limitations of SSE
- β Only supports one-way communication
- β Not supported in Internet Explorer
- β Officially tied to HTTP/1 (though workarounds exist for HTTP/2)
π§ Key Takeaway
- SSE is ideal for real-time updates from the server to the client
- Simple to implement using
EventSource
- Great for dashboards, alerts, feeds, and live content
- Supported in all major browsers (except IE)
- Use when you donβt need full duplex (bi-directional) communication
Advertisement Slot 1
Advertisement Slot 2