HTML SSE

By | February 5, 2020

SSE HTML5 contains server sent event. The server sent event is a new way for a web page to communicate with a server. It enables a browser to automatically receive data from a server via HTTP connection. When some events are sent to the server, such as submitting a form, these types of events flow from the web browser to the web server, which are called client side events. But if the information is sent to the server browser then such events are called server sent events.

The server sent event is a unidirectional, which means that data is passed from server to client in one direction.

Browser Support:-

HTML5 server cent event supports all modern browsers like Firefox Chrome Safari but Internet Explorer does not support it.

Receive SSE Notification:-

The server uses an EventSource object to receive events when an event is sent from the server.

<body>

<div id="myId"></div>

<script>

if (typeof(EventSource) !== "undefined") {
     var source = new EventSource("demo.php");
     source.onmessage = function(event){
          document.getElementById("myId").innerHTML += event.data + "<br>";
     };

} else {
     document.getElementById("myId").innerHTML = "Sorry your browser does not support server sent event";
}

</script>

</body>

Sending SSE Notification :-

In this, the data is passed to the browser by the server.

<?php 
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The current server time is: {$time}";
flush();
?>
Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *