【问题标题】:Jersey 2 Server Sent + client side Event source not working properlyJersey 2 服务器发送 + 客户端事件源无法正常工作
【发布时间】: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


    【解决方案1】:

    摸了半天,终于找到了问题所在。在这里提及,以便它可以帮助遇到相同问题的其他人。在我的服务器端 GZIP 默认启用。当我更改为按 API 压缩并排除服务器发送的压缩时,一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 2017-01-21
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多