Server Sent Event
Server Sent Event通過EventSource對象接收服務器發送事件的通知. 有三個事件message, open, error
下面的代碼演示了使用的方法
例子代碼運行環境: node.js
代碼
粘貼下面代碼運行node index.js
//index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>server-sent</title> </head> <body> <script> window.addEventListener("load",function () { let status = document.getElementById("status"); let output = document.getElementById("output"); let source; function connect() { source = new EventSource("stream");//與服務器端建立連接 //鑒定message事件, 獲取服務端發送的數據 source.addEventListener("message", function (event) { output.textContent = event.data; }, false); //監聽open事件, 判斷連接是否進行中 source,addEventListener("open", function (event) { status.textContent = '連接打開了'; },false); //監聽error事件, 處理連接錯誤的情況 source.addEventListener("error", function (event) { if (event.target.readyState === EventSource.CLOSED) { source.close(); status.textContent = '連接關閉了'; } else { status.textContent = "連接關閉了!未知錯誤!"; } }, false); } if(!!window.EventSource) { connect(); } else { status.textContent = "不支持server-sent" } },false); </script> <span id="status">Connection closed!</span> <br> <span id="output"></span> </body> </html>
服務端代碼
//index.js const http = require('http'); const fs = require('fs'); http.createServer(function (req, res) { let interval, fileName, index = "./index.html"; console.log(req.url); if(req.url === "/") { fileName = index; } else { fileName = "." + req.url; } if (fileName === "./stream") {//如果server sent event則設置相應頭信息 res.writeHead(200, { "Content-Type" : "text/event-stream", "Cache-Control" : "no-cache", "Connection": "keep-alive", }) res.write("retry: 10000\n");//過10000秒重試 res.write("data: " + (new Date()) + "\n\n"); interval = setInterval(function () { res.write("data: " + (new Date()) + "\n\n"); }, 1000); //監聽close事件, 用于停止定時器 req.connection.addListener("close", function () { clearInterval(interval); }, false); } else if (fileName === index) { //判斷是否為頁面請求, 并找到相應文件返回頁面 fs.exists(fileName, function (exists) { if (exists) { fs.readFile(fileName, function (error, content) { if (error) { res.writeHead(500); res.end(); } else { res.writeHead(200, {"Content-Type" : "text/html"}); res.end(content, "utf-8"); } }) } else { console.log(123); res.writeHead(404); res.end(); } }) } else { res.writeHead(404); res.end(); } }).listen(8080, "127.0.0.1"); console.log("at 8080");
相信看了這些案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
相關閱讀:
HTML5標簽嵌套規則的詳細介紹
瀏覽器兼容HTML5和CSS3的問題
html5做剪刀石頭布效果的教程
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com