HTTP多线程下载和断点续传

HTTP1.1协议(RFC2616)中定义了断点续传相关的HTTP头 Range和Content-Range字段

3.12  Range Units

HTTP/1.1 allows a client to request that only part (a range of) the response entity be included within the response.
HTTP/1.1 uses range units in the Range (section 14.35) and Content-Range (section 14.16) header fields. An
entity can be broken down into subranges according to various structural units.
      range-unit       = bytes-unit | other-range-unit
      bytes-unit       = "bytes"
      other-range-unit = token
The only range unit defined by HTTP/1.1 is “bytes”. HTTP/1.1 implementations MAY ignore ranges specified using
other units. HTTP/1.1 has been designed to allow implementations of applications that do not depend on knowledge
of ranges.

 

注:以下文章转载自:http://blog.chinaunix.net/u3/94343/showart_1891855.html

假设你要开发一个多线程下载工具,你会自然的想到把文件分割成多个部分,比如4个部分,然后创建4个线程,每个线程负责下载一个部分,如果文件大小为403个byte,那么你的分割方式可以为:0-99 (前100个字节),100-199(第二个100字节),200-299(第三个100字节),300-402(最后103个字节)。

      分割完成,每个线程都明白自己的任务,比如线程3的任务是负责下载200-299这部分文件,现在的问题是:线程3发送一个什么样的请求报文,才能够保证只请求文件的200-299字节,而不会干扰其他线程的任务。这时,我们可以使用HTTP1.1的Range头。Range头域可以请求实体的一个或者多个子范围,Range的值为0表示第一个字节,也就是Range计算字节数是从0开始的:
    表示头500个字节:Range: bytes=0-499
    表示第二个500字节:Range: bytes=500-999
    表示最后500个字节:Range: bytes=-500
    表示500字节以后的范围:Range: bytes=500-
    第一个和最后一个字节:Range: bytes=0-0,-1
    同时指定几个范围:Range: bytes=500-600,601-999
所以,线程3发送的请求报文必须有这一行:
    Range: bytes=200-299

     服务器接收到线程3的请求报文,发现这是一个带有Range头的GET请求,如果一切正常,服务器的响应报文会有下面这行:
HTTP/1.1 206 OK
表示处理请求成功,响应报文还有这一行
Content-Range: bytes 200-299/403
斜杠后面的403表示文件的大小,通常Content-Range的用法为:
     . The first 500 bytes:
     Content-Range: bytes 0-499/1234

     . The second 500 bytes:
     Content-Range: bytes 500-999/1234

     . All except for the first 500 bytes:
     Content-Range: bytes 500-1233/1234

     . The last 500 bytes:
     Content-Range: bytes 734-1233/1234

posted @ 2010-09-16 16:35  penink  阅读(7274)  评论(0编辑  收藏  举报