index.html
<meta charset="utf-8" />
<script src="./index.js"></script>
index.js
var source;
function init(argument){
source = new EventSource('http://localhost:9096/sse/data.php');
source.onopen = function(){
console.log('连接已经建立',this.readyState);
}
source.onmessage = function(event){
console.log('从服务器实时获取的数据',event.data);
}
source.onerror = function(){
// 出错
}
}
init();
data.php
<?php
// 以event-stream形式输出
header("Content-Type:text/event-stream;charset=utf-8");
// 只允许127.0.0.1才能够访问
header('Access-Control-Allow-Origin:http://127.0.0.1/');
echo "data:现在北京时间是".date('H:i:s')."\r\n\r\n";
?>