1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Pausing a request from a servlet's method (get, post, ...): protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Continuation continuation = ContinuationSupport.getContinuation(req); // optionally set a timeout to avoid suspending requests for too long continuation.setTimeout(0); // suspend the request continuation.suspend(); // then hold a reference for future usage from another thread continuations.offer(continuation); } // Then, from another thread which wants to send an event to the client: while (!continuations.isEmpty()) { Continuation continuation = continuations.poll(); HttpServletResponse response = (HttpServletResponse) continuation.getServletResponse(); // write to the response continuation.complete(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // Implement the doWebSocketConnect and returns an implementation of // WebSocket: public final class ReverseAjaxServlet extends WebSocketServlet { @Override protected WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { return [...] } } // Sample implementation of WebSocket: class Endpoint implements WebSocket { Outbound outbound; public void onConnect(Outbound outbound) { this.outbound = outbound; } public void onMessage(byte opcode, String data) { outbound.sendMessage("Echo: " + data); if("close".equals(data)) outbound.disconnect(); } public void onFragment(boolean more, byte opcode, byte[] data, int offset, int length) { } public void onMessage(byte opcode, byte[] data, int offset, int length) { onMessage(opcode, new String(data, offset, length)); } public void onDisconnect() { outbound = null; } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |