目录
正文
下载分为单文件下载和多文件下载,本质没有太大区别,都是使用协程,使用UnityWebRequest开启下载,可以对UnityWebRequest做一个简单封装,代码在下面,叫WebFileRequest
public class WebFileRequest : WebRequestBase, IDisposable
{
/// <summary>
/// 文件存储路径
/// </summary>
public string SavePath { private set; get; }
protected Action<long, float> onProgress;
public WebFileRequest(string url, string savePath, Action<long, float> onProgressCallback=null) : base(url)
{
SavePath = savePath;
onProgress = onProgressCallback;
}
public override IEnumerator DownLoad()
{
// Check fatal
if (States != EWebRequestStates.None)
throw new Exception($"{nameof(WebFileRequest)} is downloading yet : {URL}");
States = EWebRequestStates.Loading;
//获得文件下载长度
var headRequest = UnityWebRequest.Head(URL);
yield return headRequest.SendWebRequest();
var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));
// 下载文件
using(var CacheRequest = UnityWebRequest.Get(URL))
{
using(var fs = new FileStream(SavePath, FileMode.OpenOrCreate, FileAccess.Write))
{
var fileLen = fs.Length;
if (fileLen >= totalLength)
{
MotionLog.Log(ELogLevel.Log, $"{SavePath} download finished {fileLen}/{totalLength}");
States = EWebRequestStates.Success;
yield break;
}
CacheRequest.timeout = Timeout;
CacheRequest.downloadHandler = new DownloadHandlerFileStream(fs, 40960, fileLen, onProgress);
CacheRequest.disposeDownloadHandlerOnDispose = true;
if (fileLen > 0)
{
MotionLog.Log(ELogLevel.Log, $"resume download {URL.Substring(URL.LastIndexOf("/"))} from: {fileLen / 1024f}KB");
CacheRequest.SetRequestHeader("Range", $"bytes={fileLen}-");
fs.Seek(fileLen, SeekOrigin.Begin);
}
yield return CacheRequest.SendWebRequest();
fs.Close();
// Check error
if (CacheRequest.isNetworkError || CacheRequest.isHttpError)
{
MotionLog.LogWarning($"Failed to download web file : {URL} Error : {CacheRequest.error}");
States = EWebRequestStates.Fail;
}
else
{
States = EWebRequestStates.Success;
}
}
}
}
}
单任务下载:
IEnumerator DownloadWithSingleTask(List<PatchElement> newDownloaded)
{
foreach (var element in newDownloaded)
{
string url = _patcher.GetWebDownloadURL(element.Name);
string savePath = AssetPathHelper.MakeDownloadTempPath(element.Name);
PatchHelper.CreateFileDirectory(savePath);
// 创建下载器
using (var download = new WebFileRequest(url, savePath, OnDownloadProgress))
{
yield return download.DownLoad();
//PatchHelper.Log(ELogLevel.Log, $"Web file is download : {savePath}");
// 检测是否下载失败
if (download.States != EWebRequestStates.Success)
{
PatchEventDispatcher.SendWebFileDownloadFailedMsg(url, element.Name);
failedOnDownload = true;
yield break;
}
}
currentDownloadSizeKB += element.SizeKB;
currentDownloadCount++;
element.SavePath = savePath;
}
}
多任务下载:
可以自定义一次下载N个任务,在while循环中不断判断是否有任务完成,如果完成继续开启下一个任务,最后检查所有任务是否完成。
private class DownloadJob
{
public UnityWebRequest req;
public PatchElement info;
}
IEnumerator DownloadWithMultiTask(List<PatchElement> downloadList)
{
var maxJobs = 5;
var runningJobs = new List<DownloadJob>(maxJobs);
var lastRecordTime = Time.realtimeSinceStartup;
int assignedIdx = 0;
while (assignedIdx < downloadList.Count)
{
while (runningJobs.Count < maxJobs && assignedIdx < downloadList.Count)
{
var element = downloadList[assignedIdx];
var url = _patcher.GetWebDownloadURL(element.Name);
string savePath = AssetPathHelper.MakeDownloadTempPath(element.Name);
PatchHelper.CreateFileDirectory(savePath);
var job = UnityWebRequest.Get(url);
job.downloadHandler = new DownloadHandlerFile(savePath) { removeFileOnAbort = true };
job.SendWebRequest();
runningJobs.Add(new DownloadJob()
{
req = job,
info = element
});
assignedIdx++;
}
yield return new WaitUntil(() => CheckAnyDownloadFinished(runningJobs, ref lastRecordTime));
if (failedOnDownload) yield break;
}
yield return new WaitUntil(() => CheckAllDownloadFinished(runningJobs, ref lastRecordTime));
//clear up all request jobs
foreach(var job in runningJobs)
{
LogIfFailed(job);
job.req.Dispose();
}
runningJobs.Clear();
}
bool CheckAnyDownloadFinished(List<DownloadJob> jobs, ref float lastRecordTime)
{
long downloadedBytes = 0;
int finished = 0;
for(var i=jobs.Count-1; i>=0; i--)
{
var job = jobs[i];
if(job.req.isDone)
{
finished++;
LogIfFailed(job);
jobs.RemoveAt(i);
downloadedBytes += job.info.SizeKB;
job.req.Dispose();
}
}
if (finished>0)
{
var deltaTime = Time.realtimeSinceStartup - lastRecordTime;
currentDownloadCount += finished;
currentDownloadSizeKB += downloadedBytes;
OnDownloadProgress(downloadedBytes, downloadedBytes / deltaTime);
lastRecordTime += deltaTime;
}
return finished > 0;
}
bool CheckAllDownloadFinished(List<DownloadJob> jobs, ref float lastRecordTime)
{
long downloadedBytes = 0;
foreach(var job in jobs)
{
if (!job.req.isDone) return false;
downloadedBytes += job.info.SizeKB;
}
var deltaTime = Time.realtimeSinceStartup - lastRecordTime;
if(deltaTime > 0)
{
currentDownloadCount += jobs.Count;
currentDownloadSizeKB += downloadedBytes;
OnDownloadProgress(downloadedBytes, downloadedBytes / deltaTime);
lastRecordTime += deltaTime;
}
return true;
}
void LogIfFailed(DownloadJob job)
{
if (job.req.isHttpError || job.req.isNetworkError)
{
PatchEventDispatcher.SendWebFileDownloadFailedMsg(job.req.url, job.info.Name);
failedOnDownload = true;
MotionLog.LogWarning($"Failed to download file: {job.info.Name}.");
}
}
下面是根据平台拼接下载连接的代码,请注意,除了要区分安卓和IOS平台,还要区分用户年龄版本
游戏在中国是区分8+、12+、16+的,所以为了面对不同用户群,可能会选择不同下载连接。
public string GetWebDownloadURL(string fileName)
{
string path = $"{GetCDNServerIP()}/{fileName}";
MotionLog.Log(ELogLevel.Log, $"path is {path}");
return path;
}
public string GetCDNServerIP()
{
if (RuntimePlatform.IPhonePlayer == Application.platform)
{
return cdnurl + "/iOS";
}else if (RuntimePlatform.Android == Application.platform)
{
if (Application.identifier == "kr.co.sincetimes.gxhgkids")
{
return cdnurl + "/Android12";
}
else
{
return cdnurl + "/Android";
}
}
else
{
#if UNITY_ANDROID
if (Application.identifier == "kr.co.sincetimes.gxhgkids")
{
return cdnurl + "/Android12";
}
else
{
return cdnurl + "/Android";
}
#elif UNITY_IOS
return cdnurl + "/iOS";
#else
//return cdnurl + "/PC";
return cdnurl + "/Android";
#endif
}
}