Class ServerSentEvents

  • All Implemented Interfaces:
    Renderable

    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 ratpack.exec.stream.Streams.periodically;
    
     import static java.util.stream.Collectors.joining;
    
     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
           );
    
           context.render(ServerSentEvents.builder().build(stream));
         }).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)
             .stream()
             .map(i -> "id: " + i + "\nevent: counter\ndata: event " + i + "\n")
             .collect(joining("\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.
        Returns:
        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
        Parameters:
        context - the request handling context
        Throws:
        Exception - any