public class ServerSentEvents extends Object
renderable
object for streaming server side events.
A renderer
for this type is implicitly provided by Ratpack core.
Example usage:
import ratpack.handling.Handler; import ratpack.handling.Context; import ratpack.func.Function; import ratpack.stream.Streams; import ratpack.launch.HandlerFactory; import ratpack.launch.LaunchConfig; import ratpack.launch.LaunchConfigBuilder; import ratpack.http.client.ReceivedResponse; import ratpack.sse.ServerSentEvent; import ratpack.test.embed.EmbeddedApplication; import ratpack.test.embed.LaunchConfigEmbeddedApplication; import ratpack.test.http.TestHttpClient; import ratpack.test.http.TestHttpClients; import static ratpack.sse.ServerSentEvents.serverSentEvents; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.ScheduledExecutorService; import org.reactivestreams.Publisher; import com.google.common.collect.Lists; import com.google.common.base.Joiner; public class Example { private static EmbeddedApplication createApp() { return new LaunchConfigEmbeddedApplication() { protected LaunchConfig createLaunchConfig() { return LaunchConfigBuilder.noBaseDir().port(0).build(new HandlerFactory() { public Handler create(LaunchConfig launchConfig) { // Example of streaming chunks return new Handler() { public void handle(Context context) { // simulate streaming by periodically publishing ScheduledExecutorService executor = context.getLaunchConfig().getExecController().getExecutor(); Publisher<ServerSentEvent> eventStream = Streams.periodically(executor, 5, TimeUnit.MILLISECONDS, new Function<Integer, ServerSentEvent>() { public ServerSentEvent apply(Integer i) { if (i.intValue() < 5) { return new ServerSentEvent(i.toString(), "counter", "event " + i); } else { return null; } } }); context.render(serverSentEvents(eventStream)); } }; } }); } }; } public static void main(String[] args) { try(EmbeddedApplication app = createApp()) { ReceivedResponse response = app.getHttpClient().get(); assert response.getHeaders().get("Content-Type").equals("text/event-stream;charset=UTF-8"); List<String> outputEvents = Lists.transform(Lists.newArrayList(0, 1, 2, 3, 4), new com.google.common.base.Function<Integer, String>() { public String apply(Integer i) { return "event: counter\ndata: event " + i + "\nid: " + i + "\n"; } }); String expectedOutput = Joiner.on("\n").join(outputEvents) + "\n"; assert response.getBody().getText().equals(expectedOutput); } } }
Modifier and Type | Method and Description |
---|---|
org.reactivestreams.Publisher<? extends ServerSentEvent> |
getPublisher() |
static ServerSentEvents |
serverSentEvents(org.reactivestreams.Publisher<? extends ServerSentEvent> publisher) |
public static ServerSentEvents serverSentEvents(org.reactivestreams.Publisher<? extends ServerSentEvent> publisher)
public org.reactivestreams.Publisher<? extends ServerSentEvent> getPublisher()