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 easy to implement and works automatically in modern browsers using the EventSource API.
<!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>
<?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.
| Event Type | Purpose |
|---|---|
| message | Default event for receiving data |
| open | Fired when the connection begins |
| Error | Fired when there is a connection issue |