Advanced
HTML SSE
Using Server-Sent Events
HTML Server-Sent Events enable real-time updates from servers.
Introduction to Server-Sent Events
Server-Sent Events (SSE) is a technology that enables servers to push real-time updates to web clients. Unlike WebSockets, which allow two-way communication, SSE is a one-way channel from the server to the client. This makes it ideal for applications like real-time feeds, notifications, and live score updates.
How Server-Sent Events Work
SSE uses a persistent HTTP connection to send updates to the client whenever new data is available. Clients maintain an open connection and listen for incoming messages from the server. The server sends messages in a text/event-stream format, which the client processes in real-time.
Setting Up the Server
To use SSE, you need to configure your server to send messages in the correct format. Here is an example of how you might set up a simple Node.js server to send SSE:
Connecting to the Server from the Client
Once your server is set up, you can connect to it from the client using the EventSource
API. This API allows you to listen for messages from the server and handle them appropriately. Here is a simple example:
Handling SSE Events
The EventSource
object provides several event handlers you can use to manage incoming messages:
- onmessage: Triggered when a message is received.
- onerror: Triggered when an error occurs.
- onopen: Triggered when the connection is opened.
Advantages and Use Cases of SSE
SSE is particularly beneficial for applications requiring real-time updates from the server without the need for two-way communication. Some common use cases include:
- Live news feeds
- Stock price updates
- Social media notifications
- Collaborative editing tools
Advanced
- Previous
- Web Workers
- Next
- Browser Support