【发布时间】:2019-10-10 13:49:00
【问题描述】:
我正在使用EventSource 实现一些服务器端事件,我需要知道何时建立EventSource 连接并且服务器以初始200 OK 响应,然后我可以开始执行一些最终导致消息的其他请求从服务器通过 EventSource 发送。
我实际上使用了这个 polyfill https://github.com/AlexGalays/EventSource,它在内部使用了 XMLHttpRequest。
问题:当服务器发送 200 OK + headers 时,onreadystatechange 没有被触发(xhr.readyState 仍然是1)。这是与任何 XHR 相关的普遍问题,而不仅仅是 EventSource。
PHP 服务器示例:
<?php
sleep(5); // our actual implementation does some non-trivial startup here
// send 200 OK + headers, but no data
flush();
sleep(5);
echo "bye";
示例 - 客户:
<script>
xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => console.log(`readystate = ${xhr.readyState}`);
xhr.open('GET', 'http://localhost/longpoll.php');
xhr.send();
</script>
预期行为:
- readystate = 1(打开)
- 5 秒延迟
- readystate = 2(收到标头)
- 5 秒延迟
- 就绪状态 = 3(加载中)
- 就绪状态 = 4(完成)
实际行为:
- readystate = 1(打开)
- 10 秒延迟
- readystate = 2(收到标头)
- 就绪状态 = 3(加载中)
- 就绪状态 = 4(完成)
在最新的 Chrome (77) 和 Firefox (69) 中测试,两者的行为相同。
当我在 Chrome 开发工具 Network 选项卡中观察连接时,我确实在前 5 秒延迟后看到了响应标头和状态代码(请参阅 https://youtu.be/sIgQnbfwxjM)。这意味着浏览器在前 5 秒后真正接收到标头并更新连接状态,但 JavaScript 未被确认。
这可以通过某种方式解决吗?还是某些安全限制阻止我在此阶段获取更新的连接状态?
【问题讨论】: