Server Sent Event

Jersey itself supports SSE for years, now it is standardized as a part of JAXRS 2.1.

A simple SSE example.

@Path("events")
@RequestScoped
public class SseResource {

    @GET
    @Produces(MediaType.SERVER_SENT_EVENTS)
    public void eventStream(@Context Sse sse, @Context SseEventSink eventSink) {
        // Resource method is invoked when a client subscribes to an event stream.
        // That implies that sending events will most likely happen from different
        // context - thread / event handler / etc, so common implementation of the
        // resource method will store the eventSink instance and the application 
        // logic will retrieve it when an event should be emitted to the client.

        // sending events:
        eventSink.send(sse.newEvent("event1"));
    }    
}

Notice, you should declare @Produces value as text/event-stream( via MediaType.SERVER_SENT_EVENTS). SseEventSink should be request aware, Sse is helpful to build event payloads etc.

An example of SSE client.

The following is an example demonstrates the usage of SseBroadcaster, which allow you send messages to all registered clients.

Grab the source codes from my GitHub account, and have a try.

Last updated

Was this helpful?