SSE(Server-Sent Events)

來源  http://www.ruanyifeng.com/blog/2017/05/server-sent_events.htmlhtml

HTTP 沒法作到服務端主動推送消息,可是有一種變通方法,就是服務器向客戶端生命,接下來要發送的是流信息(streaming)服務器

也就是說,發送的不是一次性的數據包,而是一個數據流,會接二連三的發送過來,這時候客戶端不會關閉鏈接,會等待服務器發送來的新的數據流,視頻播放就是這樣的例子。本質上,這種通訊就是一流信息的方式,完成一次用時很長的下載。ui

客戶端url

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="example"></div>
<script>
  var source = new EventSource('http://127.0.0.1:8844/stream');
  var div = document.getElementById('example');
  
  source.onopen = function (event) {
    div.innerHTML += '<p>Connection open ...</p>';
  };
  
  source.onerror = function (event) {
    div.innerHTML += '<p>Connection close.</p>';
  };
  
  source.addEventListener('connecttime', function (event) {
    div.innerHTML += ('<p>Start time: ' + event.data + '</p>');
  }, false);
  
  source.onmessage = function (event) {
    div.innerHTML += ('<p>Ping: ' + event.data + '</p>');
  };
  
</script>
</body>
</html>

服務端 Node.js 實現spa

var http = require("http");

http.createServer(function (req, res) {
  var fileName = "." + req.url;

  if (fileName === "./stream") {
    res.writeHead(200, {
      "Content-Type":"text/event-stream",
      "Cache-Control":"no-cache",
      "Connection":"keep-alive",
      "Access-Control-Allow-Origin": '*',
    });
    res.write("retry: 10000\n");
    res.write("event: connecttime\n");
    res.write("data: " + (new Date()) + "\n\n");
    res.write("data: " + (new Date()) + "\n\n");

    interval = setInterval(function () {
      res.write("data: " + (new Date()) + "\n\n");
    }, 1000);

    req.connection.addListener("close", function () {
      clearInterval(interval);
    }, false);
  }
}).listen(8844, "0.0.0.0");
相關文章
相關標籤/搜索