learn2kode.in

HTML Server-Sent Events (SSE)

Server-Sent Events (SSE) allow a web page to receive continuous updates from a server over a single long-lasting HTTP connection. Unlike WebSockets, SSE is one-way: the server can send updates to the client, but the client cannot send data back through the same channel.

SSE is commonly used for:

SSE is easy to implement and works automatically in modern browsers using the EventSource API.

How Server-Sent Events Work

Basic SSE Example

Client-side (HTML + JavaScript)

<!DOCTYPE html>
<html>
<body>

<h2>Live Server Updates</h2>
<div id="result">Waiting for updates...</div>

<script>
  const source = new EventSource("server.php");

  source.onmessage = function(event) {
    document.getElementById("result").innerHTML = event.data;
  };

  source.onerror = function() {
    console.log("Connection lost or failed.");
  };
</script>

</body>
</html>

Server-side (Example in PHP)

<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");

echo "data: Server time: " . date("h:i:s") . "\n\n";
flush();
?>

This will continuously send the current time to the browser.

SSE Event Types

Event Type Purpose
message Default event for receiving data
open Fired when the connection begins
Error Fired when there is a connection issue

Advantages of SSE

Limitations of SSE