您的位置:首页 > 其它

JAX-RS Simple SSE Sample

2014-09-20 19:45 239 查看
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