首页 > html5推送中的疑问

html5推送中的疑问

html5中的server-sent event服务器推送,不是说不同与轮询的推送机制吗?
为什么还是客户端每秒发起请求呢?
正所谓“推送”,服务器应该是主动的啊,而不是客户端主动请求。
下面是我在控制台看到的情况,客户端每秒发起请求的:

即使服务端没有数据也会每秒都有请求:

客户端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>EventSource</title>
    <script type="text/javascript">
        onload=function(){
            source=new EventSource("eventsource.php");
            source.onmessage=function(event){
                  console.log(event);
            };
            /*source.onopen=function(e){
                console.log(e);
            }*/
            /*source.onerror=function(e){
                console.log(e);
            }*/
            source.addEventListener('myevent', function(e) {
                document.write(e.data+"<br>");
                console.log(e.data);
            });
        }
    </script>
</head>
<body>
    
</body>
</html>

服务端代码:

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    date_default_timezone_set('PRC');//中国
    $time = date('r');
    session_start();

    $arr=[
        'name'=>'lanyue',
        'age'=>21,
        'time'=>$time,
        'session'=>session_id()
    ];
    $json=json_encode($arr);
    //echo "data: {$json}";
    echo "event: myevent\r\n";
    echo "data: {$json}\r\n";
    echo "id: 101\r\n";
    echo "\n\n";//必须以这个结束
    ob_flush();
    flush();

问客户端代码怎么写的呗,现在明显是客户端一直在请求呀。

【热门文章】
【热门文章】