SSE减少服务器和客户端之间的延迟

时间:2015-10-06 17:32:38

标签: javascript php html html5 server-sent-events

更新:似乎整个过程都有效,但是有很长的延迟 我的问题改为"如何减少延迟"

<小时/> 我目前在利用PHP,HTML和Javascript在浏览器中显示一个页面时遇到了一些问题,该页面将POST发送到服务器,后者将SSE发送到浏览器。
我有3份文件:

的index.php

<?php
session_start();

$_SESSION['send'] = False;
$_SESSION['counter'] = 0;

echo '
<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML5 Server-Sent Events</title>
    <script type="text/javascript">
        window.onload = function(){
            var source = new EventSource("main.php");
            source.onmessage = function(event){
                document.getElementById("result").innerHTML += "Counter: " + event.data + "<br>";
            };
        };
    </script>
    <script type="text/javascript">
    function httpGetAsync(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", theUrl); 
        xmlHttp.send();
    }
    </script>
</head>
<body>
    <button type="button" onclick="httpGetAsync(\'http://localhost/click.php\')">Send</button>
    <div id="result">
        <!--Server response will be inserted here-->
    </div>
</body>
</html>';
?>

click.php

<?php
session_start();
$_SESSION['send'] = True;
?>

main.php

<?php

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
session_start();

// Send it in a message
while( 1 )
{
    if( $_SESSION['send'] == True )
    {
        $_SESSION['counter']+=1;
        echo "data: ".$_SESSION['counter']."\n\n";
        ob_end_flush();
        flush();
        $_SESSION['send'] = False;
    }
    sleep(1);
}
?>

问题是我没有收到任何SSE活动 提前感谢您的帮助。

0 个答案:

没有答案