Is it possible to create a server sent event using java servlets so that a client could receive updates using:
 <script>
   var source = new EventSource('/events');
   source.onmessage = function(e) {
     document.body.innerHTML += e.data + '<br>';
   };
 </script>
All examples I have found on the web are using PHP but I would assume that it should work using Java's HTTP Servlet.
What are Server-Sent Events? SSE definition states that it is an http standard that allows a web application to handle a unidirectional event stream and receive updates whenever the server emits data. In simple terms, it is a mechanism for unidirectional event streaming.
A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
SSE is designed to use the JavaScript EventSource API in order to subscribe to a stream of data in any popular browser. Through this interface a client requests a particular URL in order to receive an event stream. SSE is commonly used to send message updates or continuous data streams to a browser client.
An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling EventSource. close() . Once the connection is opened, incoming messages from the server are delivered to your code in the form of events.
this does the trick.
HTML
<!DOCTYPE html>
<html>
<body onload ="registerSSE()" >
    <script>
        function registerSSE()
        {
            alert('test 1');
            var source = new EventSource('http://frewper:8080/hello/sse');  
            alert('Test2');
            source.onmessage=function(event)
            {
                document.getElementById("result").innerHTML+=event.data + "<br />";
            };
            /*source.addEventListener('server-time',function (e){
                alert('ea');
            },true);*/
        }
    </script>
    <output id ="result"></output>
</body>
</html>
Servlet :
import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class sse extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    try
    {
        System.out.println("SSE Demo");
        response.setContentType("text/event-stream");
        PrintWriter pw = response.getWriter();
        int i=0;
        while(true)
        {
            i++;
            pw.write("event: server-time\n\n");  //take note of the 2 \n 's, also on the next line.
            pw.write("data: "+ i + "\n\n");
            System.out.println("Data Sent!!!"+i);
            if(i>10)
            break;
        }
        pw.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
public void doGet(HttpServletRequest request,HttpServletResponse response)  
{
    doPost(request,response);
}
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With