<form id="hz9zz"></form>
  • <form id="hz9zz"></form>

      <nobr id="hz9zz"></nobr>

      <form id="hz9zz"></form>

    1. 明輝手游網中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

      服務端主動發送數據回客戶端在H5里的完成步奏

      [摘要]我們知道,在Server Sent Event里,通過EventSource對象接收服務器發送事件的通知是有三個事件的,message, open, error這三種,今天就給大家演示一下服務端主動發送數據回客戶端在H5里的實現步奏。Server Sent EventServer Sent Eve...
      我們知道,在Server Sent Event里,通過EventSource對象接收服務器發送事件的通知是有三個事件的,message, open, error這三種,今天就給大家演示一下服務端主動發送數據回客戶端在H5里的實現步奏。

      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");


      相信看了這些案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

      相關閱讀:

      HTML5標簽嵌套規則的詳細介紹

      瀏覽器兼容HTML5和CSS3的問題

      html5做剪刀石頭布效果的教程

      以上就是服務端主動發送數據回客戶端在H5里的實現步奏的詳細內容,更多請關注php中文網其它相關文章!


      網站建設是一個廣義的術語,涵蓋了許多不同的技能和學科中所使用的生產和維護的網站。




      日韩精品一区二区三区高清