HTML5 server-sent events offer a new method for web pages to communicate with web servers. Traditionally, this has been done using the XMLHttpRequest object, which allows JavaScript to make requests to the server, but it's a one-time exchange — after the server responds, the communication ends. XMLHttpRequest is the backbone of all Ajax operations.
However, some scenarios require web pages to maintain a continuous connection to the server. For instance, stock prices on finance websites that update automatically or news tickers on media websites.
HTML5 server-sent events enable this by allowing a web page to keep an open connection to a server. This way, the server can send updates automatically without needing to reconnect and restart the server script each time.
Note: Server-Sent Events (SSE) are unidirectional, meaning data flows only from the server to the client, which is usually a web browser.
Tip: HTML5's server-sent events feature is supported by all major modern browsers such as Firefox, Chrome, Safari, and Opera, except Internet Explorer.
Let's create a PHP file named "server_time.php" with the following script. This script will regularly report the server's current time. We will retrieve and display this time on a web page later in this tutorial.
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
// Get the current time on server
$currentTime = date("h:i:s", time());
// Send it in a message
echo "data: " . $currentTime . "\n\n";
flush();
?>
The first two lines of this PHP script set important headers. The first line sets the MIME type to text/event-stream
, which is required for server-sent events. The second line disables caching to ensure the output isn't stored and reused.
Each message sent through server-sent events must begin with data:
followed by the message text and end with a newline character sequence (\n\n
).
Finally, the PHP flush()
function ensures that the data is sent immediately, rather than being buffered until the PHP script completes.
The EventSource
object is used to receive messages sent by server-sent events.
Now, let's create an HTML document named "demo_sse.html" and place it in the same directory as the "server_time.php" file. This HTML file will receive the current time from the server and display it to the user.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
window.onload = function() {
var source = new EventSource("server_time.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += "New time received from web server: " + event.data + "<br>";
};
};
</script>
</head>
<body>
<div id="result">
<!--Server response will be inserted here-->
</div>
</body>
</html>