事件源服务器已发送事件行为:在每条新消息之前打开连接

时间:2018-12-01 01:26:23

标签: javascript php html5 server-sent-events

每次我从事件源收到消息时,连接都被(重新)打开是正常的吗?

sse.js:

es = new EventSource('sse.php');

es.addEventListener('open', function(e) {
    console.log('open/Connection open');
}, false);

es.addEventListener('message', function(e) {
    console.log('message/Received: ' + e.data);
}, false);

es.addEventListener('error', function(e) {
    switch(e.readyState) {
        case EventSource.CONNECTING:
            console.log('error/Connecting...');
            break;

        case EventSource.OPEN:
            console.log('error/Connection open');
            break;

        case EventSource.CLOSED:
            console.log('error/Connection closed');
            break;
    }
}, false);

sse.php:

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    $counter = rand(1, 10);
    echo "data: {$counter}\n\n";
    echo "retry: 1000\n\n";
    ob_flush();
    flush();
?>

这是我在Chrome 70.0.3538.110 x64开发人员工具中打开控制台时得到的:

open/Connection open
message/Received: 1
open/Connection open
message/Received: 1
open/Connection open
message/Received: 6
open/Connection open
message/Received: 7
open/Connection open
message/Received: 2

这是预期的行为吗?为什么浏览器每次都会建立一个新的连接?不应该只在第一次打开连接吗?

0 个答案:

没有答案