package com.cn.test.chapter1; import org.codehaus.jettison.json.JSONArray; import javax.servlet.AsyncContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Queue; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; /** * @author Mathieu Carbou (mathieu.carbou@gmail.com) */ public final class ReverseAjaxServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 3214920223892218277L; private final Queue<AsyncContext> asyncContexts = new ConcurrentLinkedQueue<AsyncContext>(); private final Random random = new Random(); private final Thread generator = new Thread("Event generator") { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(random.nextInt(5000)); while (!asyncContexts.isEmpty()) { AsyncContext asyncContext = asyncContexts.poll(); HttpServletResponse peer = (HttpServletResponse) asyncContext.getResponse(); peer.getWriter().write(new JSONArray().put("At " + new Date()).toString()); peer.setStatus(HttpServletResponse.SC_OK); peer.setContentType("application/json"); asyncContext.complete(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } } }; @Override public void init() throws ServletException { generator.start(); } @Override public void destroy() { generator.interrupt(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext asyncContext = req.startAsync(); asyncContext.setTimeout(60000); asyncContexts.offer(asyncContext); } }
最近下载更多
xiaoding1999 LV7
2020年12月22日
0101010323 LV2
2020年9月5日
gaoxin222 LV14
2020年8月23日
wukunhua LV2
2020年7月22日
huhuhu525354 LV1
2020年7月15日
t88525 LV1
2020年5月13日
浙雨扬 LV10
2019年11月25日
Swl_124 LV2
2019年11月4日
kangdi LV10
2019年10月28日
skipple3 LV39
2019年10月15日
最近浏览更多
zeng1206 LV5
2023年12月21日
hxy19991216 LV4
2023年12月20日
1234567p LV1
2023年12月4日
edpwyg LV14
2023年11月4日
gann2015 LV24
2023年9月17日
yybb7435100 LV2
2023年8月7日
高腾达 LV3
2023年5月22日
zhiwei0127 LV1
2022年12月14日
GuoGuoX
2022年12月9日
暂无贡献等级
lioyiphy
2022年9月19日
暂无贡献等级