Web
Analytics
Server Sent Event Using JSON and Custom messages Example - Tutorial

For Consultation : +91 9887575540

Stay Connected :

CallJson.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(“Default2.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;
}
//Create Event Listener for specified event specified in default2.aspx
eventobj.addEventListener(“FirstMessage”, function (event) {
var obj = JSON.parse(event.data);
document.getElementById(‘firstmessage’).innerHTML += obj.Name;
})
}
}
</script>
</head>
<body>
<input type=”button” name=”name” value=”Call Server Sent ” onclick=”call()” />
<p id=”msgdata”></p>
<p id=”firstmessage”></p><br>
</body>
</html>

Default2.aspx

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

event: FirstMessage
data:{“Name”:”Yogesh<br />”}

Download Source Code

Select your currency