數據推送之 SSE(Server-Send Event)

服務器推送數據的新方式

這裏寫圖片描述

//index.js
var source;
function init(){
    source=new EventSource("http://localhost:8080/Comet/data.php");
    source.onopen=function(){
        console.log("連接已建立",this.readyState);//1 就是連接好的.2 就是連接完成
    }
    source.onmessage=function(event){
        document.write("<br/>從服務器實時獲取的數據",event.data);
    }
    source.onerror=function(){};
}
init();
<?php
header("Content-Type:text/event-stream;charset=utf-8");
header("Access-Control-Allow-Origin:http://127.0.0.1/");
echo "data:現在時間是:".date('H:i:s')."\r\n\r\n";
?>
//html
<meta charset="UTF-8">
<script type="text/javascript" src="index.js"></script>
<h1>SSE</h1>

然後完事;跑起來就好了 ;
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章