Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent net::ERR_INCOMPLETE_CHUNKED_ENCODING when using HTML5 Server events and Java Servlets?

i just started to play around with Server Events and i run into a chrome error message i would like to understand. i searched the web real quick but didn't find an explanation so i guess i may do something terribly wrong.

On the server side i have a simple servlet that accepts requests and creates a dummy event creator task:

private Executor executor = Executors.newSingleThreadExecutor();

public void doGet(final HttpServletRequest request, final HttpServletResponse response)
{
  final AsyncContext asynCtx = request.startAsync(request, response);

  response.setHeader("Cache-Control", "no-cache");
  response.setContentType("text/event-stream");
  response.setCharacterEncoding("utf-8");

  executor.execute(() -> {
    boolean run = true;
    try
    {
      while (run)
      {
        final ServletResponse resp = asynCtx.getResponse();
        run = resp != null;

        if (resp != null)
        {
          System.out.println("pushing a server event.");
          final PrintWriter writer = asynCtx.getResponse().getWriter();
          writer.println("data: {time: " + System.currentTimeMillis() + "}\n");
          writer.flush();
        }
        else
        {
          System.out.println("stopping beeper, no response object available anymore.");
          break; // do not run anymore, we got no response
        }

        Thread.sleep(2000);
      }
    }
    catch (final Exception e)
    {
      e.printStackTrace();
    }
  });

}

on the client i simply:

$(document).ready(function ()
{

   var source = new EventSource("/events");
   source.onmessage = function (event)
   {
     console.log("received event: " + JSON.stringify(event));
     document.getElementById("eventContainer").innerHTML += event.data + "<br/>";
   };

   console.log("start to receive events...")
});

when i load the HTML file it works fine, events are received and written to the console. But after 30 seconds i get an error message:

GET [HttpOfLocalhost]/events net::ERR_INCOMPLETE_CHUNKED_ENCODING

why?

the request than gets killed and a new one is started immediately so it doesn't kill the application but error messages on the console aren't nice.

screenshot of my developer console:

enter image description here

request/resposne details:

enter image description here

timing, this shows that it always occurs after 30 seconds:

enter image description here

Thanks!

like image 212
Chris Avatar asked Nov 11 '14 11:11

Chris


1 Answers

You can send small "no operation" (noop) chunks to keep the connection alive every 10 seconds or so.

like image 135
user951335 Avatar answered Oct 03 '22 01:10

user951335