Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript SSE减少服务器和客户端之间的延迟_Javascript_Php_Html_Server Sent Events - Fatal编程技术网

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

Javascript SSE减少服务器和客户端之间的延迟,javascript,php,html,server-sent-events,Javascript,Php,Html,Server Sent Events,更新:整个过程似乎都在运行,但存在巨大的延迟。 我的问题改为“如何减少延迟” 目前,我在一个使用PHP、HTML和Javascript的程序中遇到了一些问题,该程序在浏览器中打开一个页面,向服务器发送帖子,向浏览器发送SSE。 我有3个文档: index.php <?php session_start(); $_SESSION['send'] = False; $_SESSION['counter'] = 0; echo ' <!DOCTYPE html> <htm

更新:整个过程似乎都在运行,但存在巨大的延迟。
我的问题改为“如何减少延迟”

目前,我在一个使用PHP、HTML和Javascript的程序中遇到了一些问题,该程序在浏览器中打开一个页面,向服务器发送帖子,向浏览器发送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>';
?>

您没有ob_start,并且忘记了keep alive头。不建议将SSE与Apache一起使用,因为如果您有许多SSE连接,它可能会占用太多线程。谢谢您的输入。我已经决定切换到Node.js,从而消除了Apache和SSE。
<?php
session_start();
$_SESSION['send'] = True;
?>
<?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);
}
?>