[英]Handle large number of http requests at once in flutter
Requirement:要求:
I've 1000 URLs of PDF, from which I want to create the zip.我有 1000 个 PDF 的 URL,我想从中创建 zip。
Function:功能:
static Future<bool> downloadZip(List<String> urls) {
int counter = 0
for(String url in urls) {
bytesForFileAtUrl(url).then((bytes){
counter++;
if(bytes != null) {
//Add bytes to the zip encoder
}
if(counter == urls.length) {
//close the zip encoder
//download the zip file
}
}
}
}
static Future<Uint8List> bytesForFileAtUrl(String url) async {
try {
http.Response response = await http.get(url);
return response?.bodyBytes;
} catch (e) {
print('Error getting bytes: ${e.toString()}');
return null;
}
}
Problem:问题:
When there is small number of requests its working fine.当请求数量很少时,它的工作正常。 But in case large number of requests I'm getting the exception: SocketException: Connection failed (OS Error: Too many open files, errno = 24)
as reported here .但是,如果大量请求出现异常: SocketException: Connection failed (OS Error: Too many open files, errno = 24)
asreported here 。 This might because of memory issue on my mobile device, as its working fine on the web platform.这可能是因为我的移动设备上的内存问题,因为它在网络平台上工作正常。
I've tried other solutions like the one using Future.wait()
suggested here , but its not working and device is hanged.我已经尝试过其他解决方案,例如使用此处建议的Future.wait()
解决方案,但它不起作用并且设备挂起。
Whats the best solution for this scenario ?这种情况的最佳解决方案是什么?
Worst Solution:最坏的解决方案:
Using await keyword.使用 await 关键字。 No exception at all, but then its taking too long for the overall process to complete.一点也不例外,但是整个过程需要很长时间才能完成。
for(String url in urls) {
final bytes = await bytesForFileAtUrl(url);
...
...
}
static Future < bool > downloadZip(List < String > urls) {
int counter = 0;
urls.forEach(async() {
await bytesForFileAtUrl(url).then((bytes){
counter++;
if (bytes != null) {
//Add bytes to the zip encoder
}
if (counter == urls.length) {
//close the zip encoder
//download the zip file
}
});
});
}
static Future < Uint8List > bytesForFileAtUrl(String url) async {
try {
http.Response response = await http.get(url);
return response?.bodyBytes;
} catch (e) {
print('Error getting bytes: ${e.toString()}');
return null;
}
}
maybe try this ?也许试试这个?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.