public static class SseResource {
@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents() {
final EventOutput eventOutput = new EventOutput();
new Thread(new Runnable() {
@Override
public void run() {
try {
int i = 0;
while (latch.getCount() > 0) {
// send message with name "message-to-client" -> should be read by the client
eventOutput.write(new OutboundEvent.Builder()
.name("message-to-client")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.data(Integer.class, i)
.build());
// send another event with name "foo" -> should be ignored by the client
eventOutput.write(new OutboundEvent.Builder()
.name("foo")
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.data(String.class, "bar")
.build());
// send another un-mamed event -> should be ignored by the client
eventOutput.write(new OutboundEvent.Builder()
.mediaType(MediaType.TEXT_PLAIN_TYPE)
.data(String.class, "baz")
.build());
latch.countDown();
i++;
}
} catch (IOException e) {
throw new RuntimeException("Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (IOException ioClose) {
throw new RuntimeException("Error when closing the event output.", ioClose);
}
}
}