void OnDownload(System.Object obj) { DownloadTips tips = (DownloadTips)obj; if (tips.progress == 0) { LoadingScene.instance.StartProgress(1, 0f, tips.tips); } else { LoadingScene.instance.SetEndValue(tips.progress, tips.tips + " " + tips.speed); } }
void OnDownloadConfig(string versionValue) { string fileName = versionValue + ".zip"; string url = GameConfig.HOST_RES_ZIP() + "zip/" + fileName + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); string filePath = PathUtils.MakeFilePath(fileName, PathUtils.PathType.MobileDiskWrite); float progress = 0f; //使用流操作文件 FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); //获取文件现在的长度 long fileLength = fs.Length; //获取下载文件的总长度 //long totalLength = GetLength(url); HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Timeout = 60000; HttpWebResponse response = request.GetResponse() as HttpWebResponse; long totalLength = response.ContentLength; string size = (totalLength / 1048576f).ToString("0.00") + "MB"; string tips = "下载更新包:0/" + size; DownloadTips dt = new DownloadTips() { tips = tips }; MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0); DateTime startTime = DateTime.Now; //如果没下载完 if (fileLength < totalLength) { //断点续传核心,设置本地文件流的起始位置 fs.Seek(fileLength, SeekOrigin.Begin); //断点续传核心,设置远程访问文件流的起始位置 request.AddRange((int)fileLength); Stream stream = response.GetResponseStream(); byte[] buffer = new byte[1024]; //使用流读取内容到buffer中 //注意方法返回值代表读取的实际长度,并不是buffer有多大,stream就会读进去多少 int length = stream.Read(buffer, 0, buffer.Length); while (length > 0) { //将内容再写入本地文件中 fs.Write(buffer, 0, length); //计算进度 fileLength += length; progress = (float)fileLength / (float)totalLength; dt.tips = "下载更新包:" + (fileLength / 1048576f).ToString("0.00") + "/" + size; dt.progress = progress; dt.speed = "速度:" + (int)(fileLength / 1024f / (DateTime.Now - startTime).TotalSeconds) + "KB/s"; MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0); //类似尾递归 length = stream.Read(buffer, 0, buffer.Length); } stream.Close(); stream.Dispose(); } else { progress = 1; } fs.Close(); fs.Dispose(); //如果下载完毕,执行回调 if (progress == 1) { OnDecompressConfig(versionValue); } }