Search code examples
htmljspservletsserver-sent-events

servlet Server-sent event not working with Chrome/Safari


I am working on servlet but encountered a problem. The SSE works fine with Firefox but cannot work with Chrome/Safari. The similar code in PHP can run smoothly in all three browsers mentioned above. How to solve the problem? Thx!!

This is my servlet code:

    response.setContentType("text/event-stream;charset=UTF-8");
    response.addHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    out.print("data: " + new Date());
    out.flush();
    out.close();

And this is my JS code:

           if (typeof(EventSource) !== "undefined")
        {
            var source = new EventSource("sse");
            source.onmessage = function(event)
            {
                document.getElementById("result").innerHTML += event.data + "<br />";
                alert("ok");
            };
        }
        else
        {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
        }

BTW, i am using Glassfish.


Solution

  • you may want to modify the line out.print("data: " + new Date()); like that out.print("data: " + new Date() + " \n\n"); the browser normally gets stuck finding no double "\n" at the end of SSE data message.