Class ServerSentEvents

  • All Implemented Interfaces:

    public class ServerSentEvents
    extends Object
    implements Renderable
    A renderable object for streaming server side events.

    A renderer for this type is implicitly provided by Ratpack core.

    Example usage:

     import org.reactivestreams.Publisher;
     import ratpack.core.http.client.ReceivedResponse;
     import ratpack.core.sse.ServerSentEvent;
     import ratpack.core.sse.ServerSentEvents;
     import ratpack.test.embed.EmbeddedApp;
     import java.time.Duration;
     import java.util.Arrays;
     import java.util.Objects;
     import static;
     import static;
     import static org.junit.jupiter.api.Assertions.assertEquals;
     public class Example {
       public static void main(String[] args) throws Exception {
         EmbeddedApp.fromHandler(context -> {
           Publisher<ServerSentEvent> stream = periodically(context, Duration.ofMillis(5), i ->
             i < 5 ? ServerSentEvent.builder().id(i.toString()).event("counter").data("event " + i).build() : null
         }).test(httpClient -> {
           ReceivedResponse response = httpClient.get();
           assertEquals("text/event-stream;charset=UTF-8", response.getHeaders().get("Content-Type"));
           String expectedOutput = Arrays.asList(0, 1, 2, 3, 4)
             .map(i -> "id: " + i + "\nevent: counter\ndata: event " + i + "\n")
             + "\n";
           assertEquals(expectedOutput, response.getBody().getText());
    See Also:
    Wikipedia - Using server-sent events, MDN - Using server-sent events, builder()
    • Method Detail

      • builder

        public static ServerSentEventsBuilder builder()
        Creates a builder for an event stream.
        a builder for an event stream
      • render

        public void render​(Context context)
                    throws Exception
        Render this object to the response.
        Specified by:
        render in interface Renderable
        context - the request handling context
        Exception - any