当前位置: 移动技术网 > IT编程>移动开发>Android > Flutter Http分块下载与断点续传的实现

Flutter Http分块下载与断点续传的实现

2019年07月23日  | 移动技术网IT编程  | 我要评论

无锡液晶拼接屏,唱歌给李宗伟,电脑算命婚姻

本文来自笔者所著《flutter实战》,读者也可以点击查看在线电子版。

基础知识

http协议定义了分块传输的响应header字段,但具体是否支持取决于server的实现,我们可以指定请求头的"range"字段来验证服务器是否支持分块传输。例如,我们可以利用curl命令来验证:

bogon:~ duwen$ curl -h "range: bytes=0-10" http://download.dcloud.net.cn/hbuilder.9.0.2.macosx_64.dmg -v
# 请求头
> get /hbuilder.9.0.2.macosx_64.dmg http/1.1
> host: download.dcloud.net.cn
> user-agent: curl/7.54.0
> accept: */*
> range: bytes=0-10
#响应头
< http/1.1 206 partial content
< content-type: application/octet-stream
< content-length: 11
< connection: keep-alive
< date: thu, 21 feb 2019 06:25:15 gmt
< content-range: bytes 0-10/233295878

我们在请求头中添加"range: bytes=0-10"的作用是,告诉服务器本次请求我们只想获取文件0-10(包括10,共11字节)这块内容。如果服务器支持分块传输的话,则响应状态码为206,表示“部分内容”,并且同时响应头中变会包含”content-range“字段,如果不支持则不会包含,我们看看上面"content-range"的内容:

content-range: bytes 0-10/233295878

0-10表示本次返回的区块,233295878代表文件的总长度,单位都是byte,  也就是该文件大概233m多一点。

实现

综上所述,我们可以设计一个简单的多线程的文件分块下载器,实现的思路是:

  1. 先检测是否支持分块传输,如果不支持,则直接下载;若支持,则将剩余内容分块下载。
  2. 各个分块下载时保存到各自临时文件,等到所有分块下载完后合并临时文件。
  3. 删除临时文件。

下面是整体的流程:

// 通过第一个分块请求检测服务器是否支持分块传输 
response response = await downloadchunk(url, 0, firstchunksize, 0);
if (response.statuscode == 206) {  //如果支持
  //解析文件总长度,进而算出剩余长度
  total = int.parse(
    response.headers.value(httpheaders.contentrangeheader).split("/").last);
  int reserved = total -
    int.parse(response.headers.value(httpheaders.contentlengthheader));
  //文件的总块数(包括第一块)
  int chunk = (reserved / firstchunksize).ceil() + 1;
  if (chunk > 1) {
    int chunksize = firstchunksize;
    if (chunk > maxchunk + 1) {
      chunk = maxchunk + 1;
      chunksize = (reserved / maxchunk).ceil();
    }
    var futures = <future>[];
    for (int i = 0; i < maxchunk; ++i) {
      int start = firstchunksize + i * chunksize;
      //分块下载剩余文件 
      futures.add(downloadchunk(url, start, start + chunksize, i + 1));
    }
    //等待所有分块全部下载完成
    await future.wait(futures);
  }
  //合并文件文件 
  await mergetempfiles(chunk);
}

下面我们使用flutter下著名的http库dio的download api 实现downloadchunk:

//start 代表当前块的起始位置,end代表结束位置
//no 代表当前是第几块
future<response> downloadchunk(url, start, end, no) async {
 progress.add(0); //progress记录每一块已接收数据的长度
 --end;
 return dio.download(
  url,
  savepath + "temp$no", //临时文件按照块的序号命名,方便最后合并
  onreceiveprogress: createcallback(no), // 创建进度回调,后面实现
  options: options(
   headers: {"range": "bytes=$start-$end"}, //指定请求的内容区间
  ),
 );
}

接下来实现mergetempfiles:

future mergetempfiles(chunk) async {
 file f = file(savepath + "temp0");
 iosink iosink= f.openwrite(mode: filemode.writeonlyappend);
 //合并临时文件 
 for (int i = 1; i < chunk; ++i) {
  file _f = file(savepath + "temp$i");
  await iosink.addstream(_f.openread());
  await _f.delete(); //删除临时文件
 }
 await iosink.close();
 await f.rename(savepath); //合并后的文件重命名为真正的名称
}

下面我们看一下完整实现:

/// downloading by spiting as file in chunks
future downloadwithchunks(
 url,
 savepath, {
 progresscallback onreceiveprogress,
}) async {
 const firstchunksize = 102;
 const maxchunk = 3;

 int total = 0;
 var dio = dio();
 var progress = <int>[];

 createcallback(no) {
  return (int received, _) {
   progress[no] = received;
   if (onreceiveprogress != null && total != 0) {
    onreceiveprogress(progress.reduce((a, b) => a + b), total);
   }
  };
 }

 future<response> downloadchunk(url, start, end, no) async {
  progress.add(0);
  --end;
  return dio.download(
   url,
   savepath + "temp$no",
   onreceiveprogress: createcallback(no),
   options: options(
    headers: {"range": "bytes=$start-$end"},
   ),
  );
 }

 future mergetempfiles(chunk) async {
  file f = file(savepath + "temp0");
  iosink iosink= f.openwrite(mode: filemode.writeonlyappend);
  for (int i = 1; i < chunk; ++i) {
   file _f = file(savepath + "temp$i");
   await iosink.addstream(_f.openread());
   await _f.delete();
  }
  await iosink.close();
  await f.rename(savepath);
 }

 response response = await downloadchunk(url, 0, firstchunksize, 0);
 if (response.statuscode == 206) {
  total = int.parse(
    response.headers.value(httpheaders.contentrangeheader).split("/").last);
  int reserved = total -
    int.parse(response.headers.value(httpheaders.contentlengthheader));
  int chunk = (reserved / firstchunksize).ceil() + 1;
  if (chunk > 1) {
   int chunksize = firstchunksize;
   if (chunk > maxchunk + 1) {
    chunk = maxchunk + 1;
    chunksize = (reserved / maxchunk).ceil();
   }
   var futures = <future>[];
   for (int i = 0; i < maxchunk; ++i) {
    int start = firstchunksize + i * chunksize;
    futures.add(downloadchunk(url, start, start + chunksize, i + 1));
   }
   await future.wait(futures);
  }
  await mergetempfiles(chunk);
 }
}

现在可以进行分块下载了:

main() async {
 var url = "http://download.dcloud.net.cn/hbuilder.9.0.2.macosx_64.dmg";
 var savepath = "./example/hbuilder.9.0.2.macosx_64.dmg";
 await downloadwithchunks(url, savepath, onreceiveprogress: (received, total) {
  if (total != -1) {
   print("${(received / total * 100).floor()}%");
  }
 });
}

思考

分块下载真的能提高下载速度吗?

其实下载速度的主要瓶颈是取决于网络速度和服务器的出口速度,如果是同一个数据源,分块下载的意义并不大,因为服务器是同一个,出口速度确定的,主要取决于网速,而上面的例子正式同源分块下载,读者可以自己对比一下分块和不分块的的下载速度。如果有多个下载源,并且每个下载源的出口带宽都是有限制的,这时分块下载可能会更快一下,之所以说“可能”,是由于这并不是一定的,比如有三个源,三个源的出口带宽都为1g/s,而我们设备所连网络的峰值假设只有800m/s,那么瓶颈就在我们的网络。即使我们设备的带宽大于任意一个源,下载速度依然不一定就比单源单线下载快,试想一下,假设有两个源a和b,速度a源是b源的3倍,如果采用分块下载,两个源各下载一半的话,读者可以算一下所需的下载时间,然后再算一下只从a源下载所需的时间,看看哪个更快。

分块下载的最终速度受设备所在网络带宽、源出口速度、每个块大小、以及分块的数量等诸多因素影响,实际过程中很难保证速度最优。在实际开发中,读者可可以先测试对比后再决定是否使用。

分块下载有什么实际的用处吗?

分块下载还有一个比较使用的场景是断点续传,可以将文件分为若干个块,然后维护一个下载状态文件用以记录每一个块的状态,这样即使在网络中断后,也可以恢复中断前的状态,具体实现读者可以自己尝试一下,还是有一些细节需要特别注意的,比如分块大小多少合适?下载到一半的块如何处理?要不要维护一个任务队列?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网