【发布时间】:2019-02-10 05:15:12
【问题描述】:
我正在使用 jersey 2 来实现 server sent 。当我做一个卷曲时,我得到了正确的响应,并按预期延迟了一秒钟。但是当我尝试从客户端使用事件源时,它会等待所有事件完成,然后调用 onmessage。它还反复进行服务器调用..下面是我正在使用的服务器端和客户端代码。 服务器端球衣代码
@GET
@Path("/serverSentCheck")
@Produces(SseFeature.SERVER_SENT_EVENTS)
@ManagedAsync
public EventOutput serverSentCheck() {
final EventOutput eventOutput = new EventOutput();
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
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 | InterruptedException 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;
}
客户端事件源代码
var source = new EventSource(" https://localhost:7080/api/v1/service/serverSentCheck");
source.onmessage = function(event) {
console.log(event.data);
document.getElementById("result").innerHTML += event.data + "<br>";
};
Curl 命令运行正常
curl --insecure -H "Accept:text/event-stream" https://localhost:7080/api/v1/service/serverSentCheck
【问题讨论】:
标签: javascript java jersey-2.0 server-sent-events