Middle+
Why were server-sent events introduced in HTML5?
sobes.tech AI
Answer from AI
To implement a unidirectional communication channel between the server and the client. The server can send data to the client at any time after the connection is established.
Key features and advantages:
- Efficiency: Uses a regular HTTP connection, minimizing overhead compared to polling.
- Simplicity: Server-sent events (SSE) API is easier to use than WebSockets for unidirectional communication.
- Automatic reconnection: The browser automatically tries to reconnect if the connection is lost.
- Data type support: Supports sending text data in the
text/event-streamformat. - Browser support: Widely supported by modern browsers.
Applications:
- Real-time news feed updates.
- Event notifications (e.g., new messages).
- Real-time data monitoring (e.g., stock quotes).
- Progress updates for long-running tasks.
This is an alternative to traditional polling, where the client periodically requests updates from the server. Unlike WebSockets, SSE is unidirectional, which simplifies their use when data is only sent from the server to the client.
Client-side example (JavaScript):
const eventSource = new EventSource('/events'); // URL for receiving server events
eventSource.onmessage = function(event) {
// Handling received data
console.log('Message received:', event.data);
};
eventSource.onerror = function(error) {
// Handling connection errors
console.error('Server-Sent Events error:', error);
};
eventSource.addEventListener('customEvent', function(event) {
// Handling custom event of type 'customEvent'
console.log('Custom event received:', event.data);
});
Server-side data format example:
event: customEvent
data: {"message": "Hello!"}
data: Simple text message
id: 123 // Event identifier, used for automatic reconnection
retry: 5000 // Delay before the next reconnection in milliseconds