Server-Sent Event provides a mechanism By which, we can send the response from a server without any request. Because in the earlier time when the user asked some updates from a server (that’s called pooling) then this mechanism isn’t easily handled by the users, and for removing the burden of pooling html5 added the concept of SSE(Server-Sent Event).
Server-Sent Event is a technology that enabling a browser when a web page gets an update automatically from a server.
And in present time, a real example of SSE is- facebook /twitter updates, news feeds update, Gmail updates….etc.
Event of SSE :
It mainly has three events. And it’s called when-
- onopen --- use for connection establish.
- onmessage--- when any updates are available.
- onerror --- when any error occurs.
Properties of SSE :
- event.data
- event.message
NOTE:
- For SSE, on Server site, we must set the
Content-Type:text/event-stream
Cache-control:no-cache
- During the response from the server, output must be prefixed with “data :” string (I mean information always starts from “data:” string).
- After set the data you must add a flush() method for flushing the data and data go back to the web page.
Here we implement the simple example to gets the server response when a webpage is loaded.
<html>
<head><title> SSE Example</title>
<script>
function check_updates()
{
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("server.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, Your Browser doesn't support SSE...";
}
}
</script>
</head>
<body onload="check_updates();">
<h1>Get the updates from a Server</h1>
<div id="result"></div>
</body>
</html>
Server Site Code :
If you are using PHP language then write the below code.
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$currentTime = date('r');
echo "data:Now, The server time is: {$ currentTime } \n"; flush();
?>
If you are using ASP.NET language then write the below code.
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data:Now The server time is: " & now())
Response.Flush()
%>
"Thanks!!! for Reading"