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

Comments:

Hi Adam,

can you please show, how to provide cookies?
Neither at WebTarget nor at SseEventSource I can find any methods for providing headers.

Thanks, Frank

Posted by Frank on March 21, 2019 at 08:02 AM CET #

I'm also looking for some way to provide either header or cookie to SseEventSource requests, seems to me security does not exist in the sse client api.

Posted by Anton on June 11, 2019 at 03:33 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License