package com.oracle.gcs.pguo.examples.jaxrs.sse.simple;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
@Path("sse")
public class SimpleSseResource {
@GET
@Path("simpleEvents")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput getServerSentEvents() {
final EventOutput eventOutput = new EventOutput();
new Thread(new Runnable() {
@Override
public void run() {
try {
// push message to client every 2 seconds
// while(true) {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
eventBuilder.name("message-to-client");
eventBuilder.data(String.class, "Hello world " + i
+ "!");
final OutboundEvent event = eventBuilder.build();
eventOutput.write(event);
}
} catch (IOException e) {
throw new RuntimeException("Error when writing the event.",
e);
} finally {
try {
// no more events, closed connection
eventOutput.close();
} catch (IOException ioClose) {
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
}
}
JAX-RS Simple SSE Sample
最新推荐文章于 2022-06-20 22:03:36 发布