泽西岛 2 服务器已发送 + 客户端事件源无法正常工作



我正在使用 jersey 2 来实现服务器发送。 当我做一个卷曲时,我得到了正确的响应,并按预期延迟了一秒钟。但是当我尝试从客户端使用事件源时,它会等待所有事件完成,然后调用 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

挠了一段时间后,我才能够找出问题所在。在这里提及,以便它可以帮助遇到相同问题的其他人。在我的服务器端,默认情况下启用了 GZIP。当我更改为按 API 压缩,并从压缩中排除服务器发送时,一切正常。

最新更新