adam bien's blog

Receiving Server Sent Events (SSE) with JAX-RS 2.1 and Java EE 8 📎

To receive Server Sent Events (SSE) with a Java JAX-RS 2.1 (Java EE 8) client you will need an additional dependency:


<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-sse</artifactId>
    <version>2.26</version>
</dependency>

For the initialization of a SseEventSource you need a WebTarget which comes from a "stock" JAX-RS client:


import static java.util.concurrent.TimeUnit.SECONDS;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.sse.InboundSseEvent;
import javax.ws.rs.sse.SseEventSource;

public class SSEClientIT {

    private Client client;
    private WebTarget tut;

    @Before
    public void initClient() {
        this.client = ClientBuilder.newClient();
        this.tut = this.client.target("http://localhost:8080/sse/resources/beats");
    }
...with the target you can create a SseEventSource to register an instance of: Consumer<InboundSseEvent> as listener:

    @Test
    public void init() throws IOException {
        SseEventSource sse = SseEventSource.
            target(this.tut)
                .reconnectingEvery(2, SECONDS)
                .build();
        sse.register(this::onMessage);
        sse.open();
        
        //block here, otherwise the test method will complete
    }

    void onMessage(InboundSseEvent event) {
        String id = event.getId();
        String name = event.getName();
        String payload = event.readData();
        String comment = event.getComment();
        //processing...
    }

}
See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2