Friday Jul 25, 2014

Using Server-Sent Events (SSE) with Nothing More Than Servlet

As many of you know, HTML 5 Server-Sent Events (SSE) stands between the two extremes of completely stateless REST/HTTP and fully bidirectional WebSocket. It is a relatively simple mechanism that allows for sending data from the server to the client once a connection is established via plain HTTP. An interesting side-effect of this basic simplicity is you could conceivably use SSE with nothing more than the plain Servlet API. The downside of taking this approach is that you don't have the much higher level, easier to use specialized APIs for SSE such as the ones long included in Jersey (and now being proposed as part of Java EE 8).

The GlassFish team's own Shing Wai Chan explores the idea of using SSE from plain Servlets in an excellent recent post. The post is a very good way of understanding how SSE actually works under the hood. Besides demonstrating the basics of SSE from an HTTP perspective, the post also shows the JavaScript SSE API available on the browser as well as using the Servlet 3 async API and Java EE 7 concurrency utilities with Servlet based SSE.