Web
Analytics
HTML5 Server-Sent Events With example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Using  HTML5 Server-Sent Events our web page update its contents which are sent by web server.

Examples: Facebook updates, twitter ,  stock price updates, news feeds, cricket / election results, etc.

  1. Set “Content-Type” header to “text/event-stream”
  2. Specify that the page should not cache .
  3. Output the data to send (Always start with “data: “)
  4. Flush the output data back to the web page





Demo.html

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title></title>
<script>
function call() {
//Lets create object for Event Source
//CReate object and intilize it with null
var eventobj = null;
//To check Event Source or server sent event are supported or not
if (typeof (EventSource) == undefined) {
alert(‘Browser does not support Server Sent Event’);
}
else {
//alert(‘ this Browser support Server Sent Event’);

//Initilize object of EventSource with server page from server data will be sent
eventobj = new EventSource(“Default.aspx”);
//After successfull request for Default.aspx , the result return will be added in event argument
//onmessage is inbuilt function and executed when server sent data, now we are going to show data into HTML tag
eventobj.onmessage = function (event) {
document.getElementById(‘msgdata’).innerHTML += event.data;
}
}
}
</script>
</head>
<body>
<input type=”button” name=”name” value=”Call Server Sent ” onclick=”call()” />
<p id=”msgdata”></p>
</body>
</html>

Default.aspx

<%@ Page Language=”C#” AutoEventWireup=”true” %>
<%
Response.ContentType=”text/event-stream”;
Response.Expires = -1;
%>
retry:3000;
data: Demo at Time <%= DateTime.Now.ToLongTimeString() %>

Download Source Code