Ads 468x60px

freak2code is the blog about latest geek news,software reviews ,trends in technology and more informative stuff......

Friday 17 August 2012

Receive Server Sent Event Notifications in JAVA SERVER PAGE (JSP)


Receive Server Sent Event Notifications in JAVA SERVER PAGE (JSP)




Server-Sent Events - One Way Messaging
-------------------------------------------------------------------

A server-sent event is when a web page automatically gets updates from a server.

This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

1) Create a new EventSource object, and specify the URL of the page sending the updates (in this example "ServerSendEvent" Servelet page)
2) Each time an update is received, the onmessage event occurs
3) When an onmessage event occurs, put the received data into the element with id="result"

Create index.html
------------------------
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("ServerSendEvent");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event .data + "<br />";
};
}
else
{
document.getElementById("result").innerHTML="Sorry , your browser does not support server-sent events...";
}
</script>

</body>
</html>

-------------------------------------------------------------------------

Create New servlet page in the name of 'ServerSendEvent'

-------------------------------------------------------------------------
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Senthil Kumar
*/
public class ServerSendEvent extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Begin for session: " + request.getSession(true).getId() + " " + response.getWriter());
response.setHeader("pragma", "no-cache,no-store");
response.setHeader("cache-control", "no-cache,no-store,max-age=0,max-stale=0");

response.setContentType("text/event-stream");

PrintWriter out = response.getWriter();

int messagesSent = 0;
while (true) {
out.print("data: {" + messagesSent++ + "}\n\n");
out.flush();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println("Sent " + messagesSent);
}

0 comments:

Post a Comment

Recent Posts