例子重要功能是模仿服务器端某个软件的更新,然后客户端接收更新的数据
首先用async.html的一个函数func循环来频繁访问服务器产生线程
<!DOCTYPE html>
<html>
<head>
<title>async.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<script type="text/javascript">
function fun(){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveObject){
xhr = new ActiveObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("data").innerHTML = xhr.responseText;
fun();
}
}
}
xhr.open('GET', '/webtest/AsyncServlet');
xhr.send(null);
}
window.onload = fun;
</script>
<body>
<span id = "data">1</span>
</body>
</html>
编写webInitListener.java实现监听
package Test;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.AsyncContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener()
public class WebInitListener implements ServletContextListener{
private List<AsyncContext> asyncs = new ArrayList<AsyncContext>();
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
sce.getServletContext().setAttribute("asyncs", asyncs);
System.out.println("listen....");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep((int)(Math.random()*10000));
double num = Math.random()*10;
synchronized (asyncs) {
for(AsyncContext ctx : asyncs){
ctx.getResponse().getWriter().println("yibu : !!!! " + num);
ctx.complete();
}
asyncs.clear();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}
package Test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AsyncServlet<T> extends HttpServlet {
/**
* Constructor of the object.
*/
private List<AsyncContext> asyncs;
public AsyncServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("asyncservlet...");
AsyncContext ctx = request.startAsync();
synchronized (asyncs) {
asyncs.add(ctx);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
System.out.println("init/....");
asyncs = (List<AsyncContext>) getServletContext().getAttribute("asyncs");
}
}
最后实现效果