firefox - Jersey 服务器发送的事件不适用于 Firefox

标签 firefox jersey server-sent-events

Jersey 2.1.4、Java 8、Tomcat 8、Firefox 38.0.1

服务器:

@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput listenToBroadcast() {
    final EventOutput eventOutput = new EventOutput();
    this.broadcaster.add(eventOutput);
    return eventOutput;
}

客户:

var source = new EventSource('broadcast');
source.addEventListener('event', function(event) {
    alert('event');
}, false);
source.onopen = function() {
    alert('connection open');
};

使用 Firefox 时,连接打开警报不会在页面加载时显示。 Firefox 在控制台中显示以下错误:Firefox 无法与位于 http://localhost:8080/broadcast 的服务器建立连接. onopen 函数确实在第一个事件进入时被调用。在这种情况下,只有 onopen 函数被调用,而不是事件监听器。

Chrome 运行正常。另外,这个 demo可以正常使用 Firefox。

在页面加载时,在服务器发送事件之前,Firefox 中的“网络”选项卡显示它收到了/broadcast SSE 端点的 OK 200,但不存在 header 。 Jersey 日志显示以下连接建立信息:

o.glassfish.jersey.filter.LoggingFilter  : 11 * Server has received a request on thread http-nio-8080-exec-3
11 > GET http://localhost:8080/broadcast
11 > accept: text/event-stream
11 > accept-encoding: gzip, deflate
11 > accept-language: en-US,en;q=0.5
11 > cache-control: no-cache
11 > connection: keep-alive
11 > host: localhost:8080
11 > pragma: no-cache
11 > referer: http://localhost:8080/test_sse.html
11 > user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101     Firefox/38.0

11 * Server responded with a response on thread http-nio-8080-exec-3
11 < 200
11 < Content-Type: text/event-stream

最佳答案

我的客户端在创建 EventSource 连接后等待 EventSource.onOpen 事件 (new EventSource())。 Chrome 在连接打开后立即调用 onOpen 回调,但 Firefox 只会在服务器发送第一个事件时调用它。为了解决这个问题,我在服务器打开 SSE 连接后立即发送评论事件。 Firefox 得到这个无意义的事件,并调用 onOpen 函数。 这是我的服务器端客户端订阅代码:

@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput listenToBroadcast() {
    final EventOutput eventOutput = new EventOutput();
    this.broadcaster.add(eventOutput);

    // firefox doesn't call the EventSource.onOpen callback when the connection is created, but it requires at least one event to be sent, so a
    // meaningless comment event is used
    OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
    OutboundEvent event = eventBuilder.name("event")
            .comment("")
            .build();
    broadcaster.broadcast(event);
    return eventOutput;
}

但是,FF 仍然在控制台上显示错误:与http://localhost:8080/broadcast 的连接在页面加载时被中断。 您可以看到错误显示 using this demo 大概 a known bug

关于firefox - Jersey 服务器发送的事件不适用于 Firefox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675859/

相关文章:

java - Jersey - 用于注入(inject)的 @Context 注释。它是如何工作的?

javascript - Sencha 触摸列表分页

java - 使用 Jersey 2 的 REST API

html - 在浏览器中调试 HTML5 服务器发送的事件

php - HTML5 Server-Sent Events onerror 每 3 秒出现一次

javascript - 最大高度/最大宽度在 Firefox 和 IE 中不起作用

php - IE 10 和 Firefox 与 phpmyadmin 的问题

c# - 使用 C# 监听文本/事件流

javascript - Internet Explorer 到 Firefox javascript 迁移库 - 是否存在?

html - Flexbox 在 Firefox 上无法正常工作,但在 Chrome 和 Safari 上还可以