Give some examples and answers to them (mainly http://www.javaworld.com/javaworld/jw-02-2009/jw-02-servlet3.html?page=3 ), I want the server to send a response several times to the client without completing the request. When the request expires, I create another one, etc.
I want to avoid a lengthy poll, because I need to update the request every time I get a response. (and this is not at all what the asynchronous features of servlet 3.0 are aimed at).
I have this on the server side:
@WebServlet(urlPatterns = {"/home"}, name = "async", asyncSupported = true) public class CometServlet extends HttpServlet { public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { AsyncContext ac = request.startAsync(request, response); HashMap<String, AsyncContext> store = AppContext.getInstance().getStore(); store.put(request.getParameter("id"), ac); } }
And a stream for writing to an asynchronous context.
class MyThread extends Thread { String id, message; public MyThread(String id, String message) { this.id = id; this.message = message; } public void run() { HashMap<String, AsyncContext> store = AppContext.getInstance().getStore(); AsyncContext ac = store.get(id); try { ac.getResponse().getWriter().print(message); } catch (IOException e) { e.printStackTrace(); } } }
But when I make a request, the data is sent only if I call ac.complete() . Without this request, there will always be a timeout. So basically, I want the data to βoverflowβ before the request completes.
To make a note, I tried this with the Jetty 8 Continuation API , I also tried printing with OutputStream instead of PrintWriter . I also tried flushBuffer() when responding. Same.
What am I doing wrong?
The client side is as follows:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8080/home', true); xhr.onreadystatechange = function () { if (xhr.readyState == 3 || xhr.readyState == 4) { document.getElementById("dynamicContent").innerHTML = xhr.responseText; } } xhr.send(null);
Can someone at least confirm that the server side is ok? :)