xhr下载图片/服务器向客户端推送消息

1.不用HTML中的img标签来下载图片,通过XHR  api来下载图片:

var xhr = new XMLHttpRequest();
xhr.open('GET','/img/tooth-intro.jpg');
xhr.responseType = 'blob';   //二进制文件
xhr.onload = function(){
 if(this.status === 200){
     var img = document.createElement('img');
     img.src = window.URL.createObjectURL(this.response);
     img.onload = function(){
         //图片加载完,释放一个URL资源。
         window.URL.revokeObjectURL(this.src);
     }
     document.body.appendChild(img);
 }
}
xhr.send()

HXR满足不了流式数据的传输,但是还是有其他的办法,而且还是专门为流式数据处理和设计的,如: Server-Sent Events、和WebSocket。

2.Server-Sent Events

Server-Sent Events提供方便的流API,用于从服务器向客户端发送文本数据,判断浏览器是否支持SSE:

typeof(EventSource)!=="undefined" // true 支持;false 不支持。

客户端:

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Basic SSE Example</title>
  </head>
  <body>
    <pre id="x">Initializing...</pre>
    <script>
    var es = new EventSource("sse");
    es.addEventListener("message", function(e){
      document.getElementById("x").innerHTML += "
" + e.data;
      },false);
    </script>
  </body>
</html>

服务器:

var http = require("http"), 
    fs = require("fs");
var port = 1234;
http.createServer(function(request, response){
  console.log("Client connected:" + request.url);
  if(request.url!="/sse"){
    fs.readFile("web/basic_sse.html", function(err,file){
      response.writeHead(200, { 'Content-Type': 'text/html' });
      var s = file.toString();  //file is a buffer
      response.end(s);
      });
    return;
    }
  //Below is to handle SSE request. It never returns.
  response.writeHead(200, { "Content-Type": "text/event-stream" });
  var timer = setInterval(function(){
    var content = "data:" + new Date().toISOString() + "

";
    var b = response.write(content);
    if(!b)console.log("Data got queued in memory (content=" + content + ")");
    else console.log("Flushed! (content=" + content + ")");
    },1000);
  request.connection.on("close", function(){
    response.end();
    clearInterval(timer);
    console.log("Client closed connection. Aborting.");
    });
  }).listen(port);
console.log("Server running at http://localhost:" + port);

而WebSocket则提供了高效、双向的流机制,而且同时支持二进制和文件数据。

原文地址:https://www.cnblogs.com/liuyinlei/p/5449652.html