HTML SS Event(SSE)
The HTML5 server-sent event(SSE) enables a window browser to receive automatic updates and data from a server via HTTP connections.
we perform some event and send it to the server-side such as by submitting the form to the server. So such type of event which flows from web browser to web-server is called a client-side event. But if the server sent event some updates or details to the browser, then such events are called server-sent events. The window browser automatically updated from the Server.
Receiving events from the server:
The Server sent event(SSE) uses the EventSource object to receive events from the server. It provides the URI of the script which generates the events.
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("ServerUpdate.php");
source.onmessage = function(event) {
document.getElementById("output").innerHTML += event.data + "<br>";
}
Code Explanation:
- First, provides the new EventSource object, and define the URI of the page which sends server updates. we have taken ServerUpdate.php for sending the updates to the window web browser.
- Every time when an update occurs from the server-side, then the on message event occurs and prints the message on the web page.
- Displayed on div using id “output”.
Sending events from the server:
To work with server-sent, we need a server that can send data updates to the web browser. For this, we need to create a file in ASP, PHP, or any dynamic language.
Example: ServerUpdate.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
/Get the current time of server
$time = date('r');
echo "data: The Current Server time is: {$time}\n\n";
flush();
?>
Code Explanation:
- In the first line – set the “Content-type” header to “text/event-stream” and it is required for server-side event standards.
- The second line provides the server to turn off the caching else the server updates may be cached.
- echo “data: The Current Server time is: {$time}\n\n”; It generates the output of data to send, and it must always start with data:
- Then, we have used the flush () method, which makes sure that data is sent right away to the web page.
Example:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div{
text-align: center;
background-color: #98f5ff;
}
</style>
</head>
<body>
<h1 align="center">Dynamic Server Updates</h1>
<div id="output"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("ServerUpdate.php");
source.onmessage = function(event) {
document.getElementById("output").innerHTML += event.data + "<br>";
}
} else {
alert("Sorry, your browser does not support the server sent updates");}
</script>
</body>
</html>
OUTPUT:
Note: To execute the above code on your web browser, you need a server installed on your system, and then run this on localhost. we can install any server such as MYSQL, XAMPP, etc.
