Bhylu

Server-Sent Events API

Server-sent events provide a one-way stream of text messages from a server to a page. They can suit occasional status updates when the browser does not need a bidirectional socket.

How it works

  • EventSource connects to an endpoint responding with text/event-stream. Each message uses fields such as data: and ends with a blank line.
  • The server is an essential part of the example. A plain page cannot invent a live stream just by creating EventSource.
  • Close the connection when it is no longer needed. Proxy buffering, connection limits, authentication, and reconnect behaviour matter in a real deployment.

A practical example

HTML

<!-- index.html: serve this through your local server. -->
<p id="stream-status" role="status">Waiting for an update…</p>
<script>
  const stream = new EventSource('stream.php');
  stream.onmessage = event => {
    document.getElementById('stream-status').textContent = event.data;
    stream.close();
  };
  stream.onerror = () => {
    document.getElementById('stream-status').textContent = 'Stream unavailable.';
    stream.close();
  };
</script>

<!-- Save the PHP below in a SEPARATE file named stream.php. -->
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo "data: Workshop booking is open.\n\n";
?>

Split the two files as instructed and serve them from a PHP-capable local server. The server sends one message and the client closes. This lesson does not add a streaming endpoint to Bhylu.