How to clear xml http (xhr) response while connection is open

In my servlet I am setting the following and every second I am outputting data to the response output stream

response.setContentType("text/html");
response.addHeader("Connection", "Keep-Alive");
response.addHeader("Transfer-Encoding", "chunked");

while(true){
    Thread.sleep(1000);
    resOut.write(hello);
    resOut.flush();
}

      

In my client javascript, I have ajax

xmlhttp.onprogress = function() {
    alert(xmlhttp.responseText);
}

      

The browser gets flushed data and the warning is triggered, but the problem I'm running into is that responseText is throwing an object that is too large instead of chunks, and if I try to set the reponseType for arrybuffer or blob, etc., to an xmlhttp object. I see null until the response stream is closed from the server as expected.

So how do I clear the responseText (_read only) in between, or be able to use an arraybuffer and get chunks to make the data available in the html page while the connection is open?

+3


source to share


1 answer


As far as I know, this is how the HTTP protocol works. You won't be able to read the answer (or snippets) until it's over.

You have two workarounds:



  • You are either using a timeout or requesting a flash, so you need a pseudo state on the server (use the op id and "already flushed content" flag) - (long / short) [ http://techoctave.com/c7/posts/ 60-simple-long-polling-example-with-javascript-and-jquery] polling method.
  • Or use websockets . You can write a chunk on a socket, the client gets it and does whatever it wants with it. If you have experience with sockets from other programming languages, it will be easy for you to understand. But beware that some browsers (I'm talking about IE here) don't support it .

There may be 3, but it depends on the server language you are using. I am a .NET developer and I only know about SignalR.

0


source







All Articles