Simplest Push

When I began working more than 10 years ago, I expected push technologies from web (or application) servers. I was very disappointed when I realized that, no, there weren’t such things.

Nowadays, there are many attemps at providing push technologies. They even come from such simple technologies as HTML: aside from WebSockets, I recently learned about Server-Sent Events, another push technology brought by HTML5. Whereas WebSockets aim to provide full-duplex communication, Server-Sent Events (SSE) is just push from server to client. I just had to try it!

Of course, since HTML5 is still in editor’s draft, not all browsers are SSE compatible. This compatibility matrix shows which browser you can use with SSE. Obviously, Internet Explorer is not one of them but apart from it, it’s pretty much your choice (if you’re not mobile).

Now, SSE itself is very simple:

  • Just create an EventSource object in JavaScript on the client-side
  • Send the response with the right MIME type and format

Let’s try it. On the HTML page, we create an EventSource. The onmessage function is called whenever a new event is pushed from the server.

<script type='text/javascript'>
    var source = new EventSource("generate");
    var counter = 0;
    source.onmessage = function(event) {
        var tbody = document.getElementById('numbers').tBodies[0];
        var tr = tbody.insertRow(0);
        var counterTd = tr.insertCell(0);
        counterTd.innerHTML = counter++;
        var randomTd = tr.insertCell(1);
        randomTd.innerHTML = event.data;
    };
</script>

The above snippet will fill-in a two columns table in the page, the first column as an incremental number, the second one as the message received by SSE.

Next is the server-side. Since I’m a Java fan boy, I’ll do it with a servlet but any web technology worth its salt can be used. Notice the MIME type used ("text/event-stream") and the data prefix in the response:

public class RandomNumberServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/event-stream");
        Random random = new Random();
        PrintWriter writer = resp.getWriter();
        String next = "data:" + String.valueOf(random.nextInt(100) + 1);
        System.out.println(next);
        writer.write(next);
        writer.flush();
    }
}

Apart from the servlet mechanics and the random number generation, the code simply writes a string in the response writer.

Don’t ever forget the data prefix, else it will be treated as an error on the client-side and your onmessage function won’t be called (lost a good 30 minutes to figure that out).

That’s it folks! With these two snippets, we created the basis for a whole push application, with nothing more than simple code. Now, I wouldn’t recommend using this so long as the specs are in draft but the feature is so simple to implement it has definitely future in my eyes. Yet, the specifications are so small I would consider reading them right away.

As always, you can find here the sources for this project in Maven/Eclipse format, so you can toy with it right away!

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Simplest Push
Share this