HTML Server-Sent Events
Server-Sent Events (SSE) allow a web page to get automatic updates from a server.
What are Server-Sent Events?
SSE is a technology where a browser can receive automatic updates from a server via a single, long-lived HTTP connection. It is a one-way communication channel where events are sent from the server to the client. This is useful for applications like live news feeds, stock tickers, or sport results.
Example: Client-Side Code
The client creates a new `EventSource` object, specifying the URL of the server-side script, and listens for messages.
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}Example: Server-Side Code (PHP)
The server-side script must send a specific header (`Content-Type: text/event-stream`) and format each message with `data:` followed by the message and two newlines.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>SSE vs. WebSockets
Compared to WebSockets, which provide a two-way (bidirectional) communication channel, SSE is simpler and works over standard HTTP. It's the ideal choice for situations where you only need data to flow from the server to the client.
Test Yourself with an Exercise
What is the primary direction of communication in Server-Sent Events (SSE)?