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); } }

苏若曦 LV1
2024年10月8日
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日

txf123 LV6
3月20日
chuxue11 LV2
2024年11月18日
1561361683 LV1
2024年10月15日
c12s34g
2024年10月14日
暂无贡献等级
苏若曦 LV1
2024年10月8日
dapeioo
2024年10月8日
暂无贡献等级
qq970040477 LV24
2024年5月26日
zeng1206 LV7
2023年12月21日
hxy19991216 LV4
2023年12月20日
1234567p LV1
2023年12月4日