通过使用SSE协议简单实现服务器和客户端 - 在JAVA语言中

时间:2016-02-28 15:23:29

标签: java api rest jersey jetty

我正在寻找通过JAVA语言使用SSE(简单发送事件)协议来简单实现服务器和客户端。我知道可能通过jetty或jersy,但寻找简单的例子来开始。

1 个答案:

答案 0 :(得分:3)

您可以这样做:

添加泽西的依赖或添加jar

在项目中添加依赖项或添加jar,如

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-sse</artifactId>
</dependency>

然后为服务器创建一个类:

@Path("events")
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 {
                        for (int i = 0; i < 10; i++) {
                            // ... code that waits 1 second
                            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 {
                            eventOutput.close();
                        } catch (IOException ioClose) {
                            throw new RuntimeException(
                                "Error when closing the event output.", ioClose);
                        }
                    }
                }
            }).start();
            return eventOutput;
        }
}

然后在客户端上使用以下代码:

Client client = ClientBuilder.newBuilder()
        .register(SseFeature.class).build();
WebTarget target = client.target("http://localhost:9998/events");

EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
    final InboundEvent inboundEvent = eventInput.read();
    if (inboundEvent == null) {
        // connection has been closed
        break;
    }
    System.out.println(inboundEvent.getName() + "; "
        + inboundEvent.readData(String.class));
}

通过简单的示例检查以下链接以及详细信息。

https://jersey.java.net/documentation/latest/sse.html

http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/

http://en.kodcu.com/2013/11/jaxrs-2-html-5-server-sent-events-on-glassfish-4/