Firefox 未收到 EventSource 消息

EventSource messages not received in Firefox

我有一个发送测试 EventSource 消息的服务器,如下所示:

要求:

GET /web/stream/status HTTP/1.1
Host: localhost:1010
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: text/event-stream
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:1010/web/
Cookie: JSESSIONID=1miz08s4nu74q11sm7y44uwu2b
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

回复:

HTTP/1.1 200 OK
Content-Type: text/event-stream;charset=UTF-8
Connection: close
Server: Jetty(9.0.6.v20130930)

event: data
data: hello

所有行都以 \r\n 结尾。所以这对我来说是正确的,但如果我在 Firefox 中尝试这个...

var source = new EventSource('/web/stream/status');
source.onmessage = function(event) { console.log(event); };
source.onerror = function(event) { console.log(event); };

... 然后它完全按照上面的方式连接并执行请求(事实上我将会话从 Wireshark 复制到 telnet 以测试它),并且根据 Wireshark 发送了 event: data 东西,但两者都没有调用 onmessageonerror 处理程序。 onerror 在我停止服务器时调用。

网络事物的“响应”选项卡中从未显示任何数据。

有没有人知道哪里出了问题?

啊哈,我找到了答案! Firefox 不喜欢;charset=UTF-8。规范说您可以拥有 Firefox 允许的 ;charset=utf-8

对规范的解释相当严格,但足够公平。

此外,只有 onmessage()data: 行。如果 data: 前面有 event: 名称,则不会调用 onmessage() - 相反,您必须使用此:

source.addEventListener('name_of_my_event', myEventHandler, false);