本文來自筆者所著《Flutter實戰》,讀者也能夠點擊查看在線電子版。git
Http協議定義了分塊傳輸的響應header字段,但具體是否支持取決於Server的實現,咱們能夠指定請求頭的"range"字段來驗證服務器是否支持分塊傳輸。例如,咱們能夠利用curl命令來驗證:github
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"的內容:macos
Content-Range: bytes 0-10/233295878
複製代碼
0-10表示本次返回的區塊,233295878表明文件的總長度,單位都是byte, 也就是該文件大概233M多一點。bash
綜上所述,咱們能夠設計一個簡單的多線程的文件分塊下載器,實現的思路是:服務器
下面是總體的流程:markdown
// 經過第一個分塊請求檢測服務器是否支持分塊傳輸
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); //合併後的文件重命名爲真正的名稱
}
複製代碼
下面咱們看一下完整實現:app
/// 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);
}
}
複製代碼
如今能夠進行分塊下載了:curl
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源下載所需的時間,看看哪一個更快。
分塊下載的最終速度受設備所在網絡帶寬、源出口速度、每一個塊大小、以及分塊的數量等諸多因素影響,實際過程當中很難保證速度最優。在實際開發中,讀者可能夠先測試對比後再決定是否使用。
分塊下載有什麼實際的用處嗎?
分塊下載還有一個比較使用的場景是斷點續傳,能夠將文件分爲若干個塊,而後維護一個下載狀態文件用以記錄每個塊的狀態,這樣即便在網絡中斷後,也能夠恢復中斷前的狀態,具體實現讀者能夠本身嘗試一下,仍是有一些細節須要特別注意的,好比分塊大小多少合適?下載到一半的塊如何處理?要不要維護一個任務隊列?