server_sent_event.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>获得服务器更新</h1>
<div id="result"></div>
<script type="text/javascript">
if(typeof(EventSource)!=="undefined"){//判断浏览器是否支持EventSource
var source = new EventSource("ServerServlet");//创建一个新的 EventSource对象,
//然后规定发送更新的页面的URL(本例中是 "server.jsp")
source.onmessage=function(event){//每接收到一次更新,就会发生 onmessage事件
document.getElementById("result").innerHTML=event.data;//把已接收的数据推入 id 为 "result" 的元素中
};
}else{
document.getElementById("result").innerHTML="sorry,your browser doesn't support event source";
}
</script>
</body>
</html>
ServerServlet.java
package com.servlet.test;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServerServlet
*/
public class ServerServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Content-Type", "text/event-stream");//设置服务器端事件流
response.setHeader("Cache-Control","no-cache");//规定不对页面进行缓存
PrintWriter pw = response.getWriter();
//each message that we send must ends with \n\n,被坑苦了........
pw.write("data: " + new Date() +"\n\n");//输出发送日期(始终以 "data: " 开头),
pw.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
参考链接
http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/
http://milestonenext.blogspot.hk/2013/07/html5-server-sent-events-sample-with.html