本文來自筆者所著《Flutter實(shí)戰(zhàn)》,讀者也可以點(diǎn)擊查看在線電子版。
基礎(chǔ)知識(shí)
Http協(xié)議定義了分塊傳輸?shù)捻憫?yīng)header字段,但具體是否支持取決于Server的實(shí)現(xiàn),我們可以指定請(qǐng)求頭的"range"字段來驗(yàn)證服務(wù)器是否支持分塊傳輸。例如,我們可以利用curl命令來驗(yàn)證:
bogon:~ duwen$ curl -H "Range: bytes=0-10" http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg -v# 請(qǐng)求頭> 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#響應(yīng)頭< 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
我們?cè)谡?qǐng)求頭中添加"Range: bytes=0-10"的作用是,告訴服務(wù)器本次請(qǐng)求我們只想獲取文件0-10(包括10,共11字節(jié))這塊內(nèi)容。如果服務(wù)器支持分塊傳輸?shù)脑挘瑒t響應(yīng)狀態(tài)碼為206,表示“部分內(nèi)容”,并且同時(shí)響應(yīng)頭中變會(huì)包含”Content-Range“字段,如果不支持則不會(huì)包含,我們看看上面"Content-Range"的內(nèi)容:
Content-Range: bytes 0-10/233295878
0-10表示本次返回的區(qū)塊,233295878代表文件的總長(zhǎng)度,單位都是byte, 也就是該文件大概233M多一點(diǎn)。
實(shí)現(xiàn)
綜上所述,我們可以設(shè)計(jì)一個(gè)簡(jiǎn)單的多線程的文件分塊下載器,實(shí)現(xiàn)的思路是:
下面是整體的流程:
// 通過第一個(gè)分塊請(qǐng)求檢測(cè)服務(wù)器是否支持分塊傳輸 Response response = await downloadChunk(url, 0, firstChunkSize, 0);if (response.statusCode == 206) { //如果支持 //解析文件總長(zhǎng)度,進(jìn)而算出剩余長(zhǎng)度 total = int.parse( response.headers.value(HttpHeaders.contentRangeHeader).split("/").last); int reserved = total - int.parse(response.headers.value(HttpHeaders.contentLengthHeader)); //文件的總塊數(shù)(包括第一塊) 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庫(kù)dio的download API 實(shí)現(xiàn)downloadChunk:
//start 代表當(dāng)前塊的起始位置,end代表結(jié)束位置//no 代表當(dāng)前是第幾塊Future<Response> downloadChunk(url, start, end, no) async { progress.add(0); //progress記錄每一塊已接收數(shù)據(jù)的長(zhǎng)度 --end; return dio.download( url, savePath + "temp$no", //臨時(shí)文件按照塊的序號(hào)命名,方便最后合并 onReceiveProgress: createCallback(no), // 創(chuàng)建進(jìn)度回調(diào),后面實(shí)現(xiàn) options: Options( headers: {"range": "bytes=$start-$end"}, //指定請(qǐng)求的內(nèi)容區(qū)間 ), );}
接下來實(shí)現(xiàn)mergeTempFiles:
Future mergeTempFiles(chunk) async { File f = File(savePath + "temp0"); IOSink ioSink= f.openWrite(mode: FileMode.writeOnlyAppend); //合并臨時(shí)文件 for (int i = 1; i < chunk; ++i) { File _f = File(savePath + "temp$i"); await ioSink.addStream(_f.openRead()); await _f.delete(); //刪除臨時(shí)文件 } await ioSink.close(); await f.rename(savePath); //合并后的文件重命名為真正的名稱}
下面我們看一下完整實(shí)現(xiàn):
/// Downloading by spiting as file in chunksFuture 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); }}
現(xiàn)在可以進(jìn)行分塊下載了:
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()}%"); } });}
思考
分塊下載真的能提高下載速度嗎?
其實(shí)下載速度的主要瓶頸是取決于網(wǎng)絡(luò)速度和服務(wù)器的出口速度,如果是同一個(gè)數(shù)據(jù)源,分塊下載的意義并不大,因?yàn)榉?wù)器是同一個(gè),出口速度確定的,主要取決于網(wǎng)速,而上面的例子正式同源分塊下載,讀者可以自己對(duì)比一下分塊和不分塊的的下載速度。如果有多個(gè)下載源,并且每個(gè)下載源的出口帶寬都是有限制的,這時(shí)分塊下載可能會(huì)更快一下,之所以說“可能”,是由于這并不是一定的,比如有三個(gè)源,三個(gè)源的出口帶寬都為1G/s,而我們?cè)O(shè)備所連網(wǎng)絡(luò)的峰值假設(shè)只有800M/s,那么瓶頸就在我們的網(wǎng)絡(luò)。即使我們?cè)O(shè)備的帶寬大于任意一個(gè)源,下載速度依然不一定就比單源單線下載快,試想一下,假設(shè)有兩個(gè)源A和B,速度A源是B源的3倍,如果采用分塊下載,兩個(gè)源各下載一半的話,讀者可以算一下所需的下載時(shí)間,然后再算一下只從A源下載所需的時(shí)間,看看哪個(gè)更快。
分塊下載的最終速度受設(shè)備所在網(wǎng)絡(luò)帶寬、源出口速度、每個(gè)塊大小、以及分塊的數(shù)量等諸多因素影響,實(shí)際過程中很難保證速度最優(yōu)。在實(shí)際開發(fā)中,讀者可可以先測(cè)試對(duì)比后再?zèng)Q定是否使用。
分塊下載有什么實(shí)際的用處嗎?
分塊下載還有一個(gè)比較使用的場(chǎng)景是斷點(diǎn)續(xù)傳,可以將文件分為若干個(gè)塊,然后維護(hù)一個(gè)下載狀態(tài)文件用以記錄每一個(gè)塊的狀態(tài),這樣即使在網(wǎng)絡(luò)中斷后,也可以恢復(fù)中斷前的狀態(tài),具體實(shí)現(xiàn)讀者可以自己嘗試一下,還是有一些細(xì)節(jié)需要特別注意的,比如分塊大小多少合適?下載到一半的塊如何處理?要不要維護(hù)一個(gè)任務(wù)隊(duì)列?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注