html5推送中的疑问
大家讲道理
大家讲道理 2017-04-17 13:09:09
0
2
587

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();
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
伊谢尔伦

Ask the client how to write the code. Now it is obvious that the client has been requesting.

巴扎黑

Please refer to the link description I answered before

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!