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:
request/resposne details:
timing, this shows that it always occurs after 30 seconds:
Thanks!
Ok, so i couldn't stand still and look closer whats happening.
The AsyncContext object has a setTimeout(...) method. Per default in my version of tomcat (Tomcat embedded 8) the value is set to 30,000 ms (30 seconds). That's exactly the duration after i got the net::ERR_INCOMPLETE_CHUNKED_ENCODING error in my chrome console.
i checked using:
which showed:
so to avoid the net:ERR message someone could set the timeout to 0. But than the event thread keeps running forever (unfortunately). Another solution, which i used, is to add a AsyncListener to the AsyncContext and call the complete() method inside the onTimeout() method.
from the API doc of the complete() method:
the source code of my listener:
so yes, it was due lack of knowledge. i hope this is helpful for someone.