Skip to main content

Server-Sent Events (SSE) in GlassFish

Posted by jitu on April 20, 2012 at 11:26 AM PDT

Server-Sent Events (SSE) is part of HTML5 specifications that can be used to push notifications from a server on a HTTP connection. A developer can implement it on top of a servlet but he has to know the details of wire format. We added bit of abstraction so that a developer doesn't have to deal with the wire level details and can work on actual application.

The heart of the abstraction is a handler for SSE connections that can be designated to handle connections for a path. For example, NotificationsHandler handles connections for "/notifications" path.

@ServerSentEvent("/notifications")
public class NotificationsHandler extends ServerSentEventHandler {
    public void onConnected(ServerSentEventConnection client) {
    }
    public void sendMessage(String data) {
        connection.sendMessage(data);
    }
}

Yes, there is a context as usual and which can be used to get all the current connections for a path. So if the server wants to push a notification to all the clients, it can do so easily. It uses CDI so that it can be injected in a CDI bean. For example, context for "/notifications" is injected into a servlet

public class PlayerServlet extends HttpServlet {
    @Inject @ServerSentEventContext("/notifications")
    ServerSentEventHandlerContext ctxt;

    private void sendEvent(String event) {
        for(NotificationsHandler handler : ctxt.getHandlers()) {
            handler.sendMessage(...);
        }
    }
}

For more details, take a look at the API and implementation in the web-sse module in the GlassFish trunk. There is a SSE sample app in the trunk. There are also plans to support path templates (say, "/chat/{room}") like JAX-RS.