使用Node.js实现HTTP 206内容分片的教程

2020-06-17 06:47:38易采站长站整理

这里有一对有2048个字节文件的例子。注意省略起点和重点的区别。

请求开始的1024个字节

浏览器发送:
 


GET /dota2/techies.mp4 HTTP/1.1
Host: localhost:8000
Range: bytes=0-1023

服务器返回:
 


HTTP/1.1 206 Partial Content
Date: Mon, 15 Sep 2014 22:19:34 GMT
Content-Type: video/mp4
Content-Range: bytes 0-1023/2048
Content-Length: 1024

(Content...)

没有终点位置的请求

浏览器发送:
 


GET /dota2/techies.mp4 HTTP/1.1
Host: localhost:8000
Range: bytes=1024-

服务器返回:
 


HTTP/1.1 206 Partial Content
Date: Mon, 15 Sep 2014 22:19:34 GMT
Content-Type: video/mp4
Content-Range: bytes 1024-2047/2048
Content-Length: 1024

(Content...)

注意:服务器并不需要在单个响应中返回所有剩下的字节,特别是当正文太长或者有其他性能的考虑。所以下面的两个例子在这种情况下也是可接受的:
 


Content-Range: bytes 1024-1535/2048
Content-Length: 512

服务器仅返回剩余正文的一半。下一次请求的范围将从第1536个字节开始。

 


Content-Range: bytes 1024-1279/2048
Content-Length: 256

服务器仅返回剩余正文的256个字节。下一次请求的范围将从第1280个字节开始。

请求最后512个字节

浏览器发送:
 


GET /dota2/techies.mp4 HTTP/1.1
Host: localhost:8000
Range: bytes=-512

服务器返回:
 


HTTP/1.1 206 Partial Content
Date: Mon, 15 Sep 2014 22:19:34 GMT
Content-Type: video/mp4
Content-Range: bytes 1536-2047/2048
Content-Length: 512

(Content...)

请求不可用的范围:

浏览器发送:
 


GET /dota2/techies.mp4 HTTP/1.1
Host: localhost:8000
Range: bytes=1024-4096

服务器返回:
 


HTTP/1.1 416 Requested Range Not Satisfiable
Date: Mon, 15 Sep 2014 22:19:34 GMT
Content-Range: bytes */2048

理解了工作流和头部信息后,现在我们可以用Node.js去实现这个机制。

开始用Node.js实现

第一步:创建一个简单的HTTP服务器

我们将像下面的例子那样,从一个基本的HTTP服务器开始。这已经可以基本足够处理大多数的浏览器请求了。首先,我们初始化我们需要用到的对象,并且用initFolder来代表文件的位置。为了生成Content-Type头部,我们列出文件扩展名和它们相对应的MIME名称来构成一个字典。在回调函数httpListener()中,我们将仅允许GET可用。如果出现其他方法,服务器将返回405 Method Not Allowed,在文件不存在于initFolder,服务器将返回404 Not Found。