更新:似乎整个过程都有效,但是有很长的延迟
我的问题改为"如何减少延迟"
<?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活动 提前感谢您的帮助。