Sobes.tech
Middle

Why are server-sent events introduced in HTML5?

sobes.tech AI

Answer from AI

Server-sent events (SSE) were introduced in HTML5 for unidirectional data transfer from server to client in real-time over an HTTP connection. This allows receiving updates from the server without the need for the client to constantly send requests (polling). The main advantages compared to other technologies:

  • Simplicity: Uses a regular HTTP connection, which simplifies integration with existing web technologies and infrastructure.
  • Efficiency: Allows the server to send data when it is ready, reducing network and server load compared to frequent polling.
  • Automatic Reconnection: The browser automatically attempts to restore the connection if it is lost.
  • Built-in Handling: The EventSource API in the browser provides a simple interface for working with events and data.

Example of client-side usage:

// Create a new EventSource object, specifying the server URL for SSE
const eventSource = new EventSource('/updates');

// Handle the 'message' event - receiving data from the server
eventSource.onmessage = function(event) {
  // Log the received data
  console.log('New data from server:', event.data);
};

// Handle connection errors
eventSource.onerror = function(error) {
  console.error('An error occurred:', error);
};

On the server, the response should have the MIME type text/event-stream and be formatted as follows:

data: This is the first line of data\n
data: This is the second line\n\n

Each message ends with two newline characters (\n\n). Each data line starts with data: . There can be other fields as well, such as event: to specify the event type or id: for message identifiers.

Server-sent events are a good choice for scenarios where the server needs to send a stream of updates to the client, such as notifications, news feeds, stock quotes, or the results of long-running processes. They are simpler to implement than WebSockets for unidirectional communication.

Why are server-sent events introduced in HTML5… - sobes.tech