Tuesday, July 9, 2013

HTML5 Server-Sent Events Sample with Java Servlet as Event Server

Document  Version 1.0

Copyright © 2012-2013 beijing.beijing.012@gmail.com



Server-Sent Events is a HTML5 feature which support browse to update page content automatically.

I will show a Server-Sent Events sample which get update of serve time automatically. Server side implementation is a Java Servlet running on Tomcat.


1. Create a simple web application:







2. Create a 3.X style Java Servlet "SseServer.java"




package sse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author swang
 *
 */
@WebServlet("/SseServer")
public class SseServer extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Besides "text/event-stream;", Chrome also needs charset, otherwise
// does not work
// "text/event-stream;charset=UTF-8"
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");

PrintWriter out = response.getWriter();

while (true) {
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + new Date().toLocaleString() + "\n\n");
out.flush();
// out.close(); //Do not close the writer!
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}



Make sure in the Servlet, set content type of response as "text/event-stream;charset=UTF-8", and NOT
just "text/event-stream". Otherwise it does not work with Chrome. 



3.  Create a SSE.html file




<!DOCTYPE html>
<html>
<body>
<h1>Current Server Time  : </h1>

<div id="ServerTime"></div>

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

</body>
</html>



4. Deploy the Web Application


Export the Web Application as "SSE.war", and deploy it to a running Tomcat Server.


5. Try accessing the SSE.html use browser


Access the SSE.html using link http://localhost:8080/SSE/SSE.html

Your browser should shown content as below:




When every 5 seconds, there is new line shown in your browser, congratulations, you have made your first Server-Sent Events Application!




7 comments:

  1. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  2. In Firefox 20.0, the interval is 10 seconds. In Chrome 27.0.1453.110, the interval is 8 seconds.

    I think the browser has it basic interval for pulling the date from server.

    ReplyDelete
  3. if i am passing a message to data field why a file is getting downloaded

    ReplyDelete
  4. Hello!
    I was wondering if there is a way to do not update page every 5 sec but to call servlet from other java code and to get page updated on this call event. I tryied to do it but with no luck.
    Thanks in advance!

    ReplyDelete
  5. Sounds like the client is polling the server, but these are actually re-connections. The server should be pushing data down the wire on some server event. The client should be making one connection, not a connection every 20 or 8 seconds. I believe there is still work to be done. Thanks for your demo !

    ReplyDelete
  6. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete