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();
}
}
}
}
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>
<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!
Works Great...Thanks!
ReplyDeleteIn Firefox 20.0, the interval is 10 seconds. In Chrome 27.0.1453.110, the interval is 8 seconds.
ReplyDeleteI think the browser has it basic interval for pulling the date from server.
if i am passing a message to data field why a file is getting downloaded
ReplyDeleteHello!
ReplyDeleteI 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!
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 !
ReplyDeleteThis blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
ReplyDeletepython training in chennai
python course in chennai
python training in bangalore
A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
ReplyDeleteAWS Training in Bangalore
AWS training in sholinganallur
AWS training in Tambaram
AWS training in Velachery
Great Post,really it was very helpful for us.
ReplyDeleteThanks a lot for sharing!
I found this blog to be very useful!!
Hadoop training in Bangalore
https://www.apponix.com/Big-Data-Institute/hadoop-training-in-bangalore.html
Gobeithio y daw'r lwc i chi. Wish i chi bob amser yn hapus!
ReplyDeleteLều xông hơi khô
Túi xông hơi cá nhân
Lều xông hơi hồng ngoại
Mua lều xông hơi
Vanskeligheter( van bướm ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van an toàn ) er det som til slutt( van bướm tay quay ) vil fjerne himmelen.
ReplyDeleteCognex is the AWS Training in chennai. Cognex offers so many services according to the students requriments.
ReplyDelete