void OnfragmentDownloaded(HTTPRequest req, HTTPResponse resp) { if (resp == null) { ++Cnt; if (Cnt < 3) { StartDownload(); } else { Debug.LogError("Download Failed!"); } return; } downloadedFragments = resp.GetStreamedFragments(); if (downloadedFragments != null) { if (Download_now) { download_now(downloadedFragments); } Begin = true; } if (resp.IsStreamingFinished) { Debug.Log("Download Finished!"); } }
private void ProcessDownloadedData(HTTPRequest request, HTTPResponse response) { //Debug.Log("Processing downloaded data"); if (request == null || response == null) { return; } if (!mRequestToBytesDownloaded.ContainsKey(request)) { mRequestToBytesDownloaded[request] = 0; } if (!response.IsStreamed) { byte[] data = response.Data; // Copy data into memory int offset = response.GetRange().FirstBytePos + mRequestToBytesDownloaded[request]; int length = data.Length; CopyDownloadedFragment(offset, length, ref data); // Keep track of how many bytes this connection downloaded & consecutive bytes Interlocked.Add(ref mDownloadedContentSize, length); Interlocked.Add(ref mConsecutiveBytesCount, length); mDownloadComplete = mConsecutiveBytesCount >= mContentSize && mContentSize > 0; } else { List <byte[]> fragments = response.GetStreamedFragments(); if (fragments == null) { return; } for (int i = 0; i < fragments.Count; i++) { byte[] fragment = fragments[i]; // Copy data into memory int offset = response.GetRange().FirstBytePos + mRequestToBytesDownloaded[request]; int length = fragment.Length; CopyDownloadedFragment(offset, length, ref fragment); // Keep track of how many bytes this connection downloaded & consecutive bytes Interlocked.Add(ref mDownloadedContentSize, length); mRequestToBytesDownloaded[request] += length; Interlocked.Add(ref mConsecutiveBytesCount, length); mDownloadComplete = mConsecutiveBytesCount >= mContentSize && mContentSize > 0; } } }
/// <summary> /// 处理下载的数据 /// </summary> /// <param name="saveFileName">完整的保存路径.包含文件名</param> /// <param name="response"></param> /// <param name="downloadItemModel">下载数据模型</param> private void ProgressDownloadData(string saveFileName, HTTPResponse response, DownloadItemModel downloadItemModel) { // 记录 上一次的下载量 long lastDownloadedSize = downloadItemModel.DownloadedSize; int downloadedSize = 0; List <byte[]> byteses = response.GetStreamedFragments(); if (byteses != null) { int byteCount = byteses.Count; for (int i = 0; i < byteCount; i++) { downloadedSize += byteses[i].Length; } } // 记录已经下载的长度 downloadItemModel.DownloadedSize = downloadItemModel.DownloadedSize + downloadedSize; ProcessFragments(byteses, saveFileName); if (downloadItemModel.DownloadedSize >= downloadItemModel.DownloadSize) { downloadItemModel.IsDownloadFinsh = true; } else { downloadItemModel.IsDownloadFinsh = false; } // 记录当前的时间 downloadItemModel.ThisDownloadTimeSpan = Time.realtimeSinceStartup; // 计算等待时间的长度 float waitingTimeLength = downloadItemModel.ThisDownloadTimeSpan - downloadItemModel.LastDownloadTimeSpan; long downloadSizeDifference = downloadItemModel.DownloadedSize - lastDownloadedSize; downloadItemModel.DownloadSpeedValue = SpeedCalculator(downloadSizeDifference, waitingTimeLength); downloadItemModel.LastDownloadTimeSpan = downloadItemModel.ThisDownloadTimeSpan; // 设置下载进度 百分比 downloadItemModel.DownloadProgressValue = (downloadItemModel.DownloadedSize * 1.0f / downloadItemModel.DownloadSize) * 100f; // 更新下载进度 UpdateSpeedValue(downloadItemModel); // 保存下载数据进度 SaveProcessFragmentsData(downloadItemModel); }
void OnFragmentDownloaded(HTTPRequest req, HTTPResponse resp) { Manifest metadata = (Manifest)req.Tag; // HTTP requests need to have a Manifest attached to them to be valid // might have happened if it was an early abort, before a connection was set if (metadata == null) { req.Abort(); return; } if (resp != null) { metadata.ResponseCode = resp.StatusCode; } if (resp == null || resp.StatusCode >= 400 || req.Exception != null || req.Response == null) { metadata.SetError(ManifestErrors.UnknownDownloadError); if (OnEngineDownloadFailed != null) { OnEngineDownloadFailed(metadata); } metadata.EngineInstance = null; req.Tag = null; return; } metadata.Ping(); List <byte[]> downloadedFragments = resp.GetStreamedFragments(); if (downloadedFragments != null) { metadata.__Update(downloadedFragments); downloadedFragments.Clear(); } if (resp.IsStreamingFinished) { metadata.EngineInstance = null; req.Tag = null; if (OnEngineDownloadFinished != null) { OnEngineDownloadFinished(metadata); } } }
private void OnDownloadProcessing(HTTPRequest request, HTTPResponse response) { Debug.Assert(response != null); Debug.Log("Processing request from " + request.Uri.AbsoluteUri); RemoteFileFragmentMetadata fragmentMetadata = m_RemoteFileMetadata.GetFileFragmentDataFromUri(request.Uri.AbsoluteUri); Debug.Log("Fragment index: " + fragmentMetadata.index); lock (fragmentMetadata) { if (!response.HasStreamedFragments()) { return; } List <byte[]> fragmentBytesList = response.GetStreamedFragments(); //if (lastDownloadedURI == request.Uri.AbsoluteUri) { // Debug.LogWarning("Download callback called twice in a row -- ignoring the second one"); // return; //} if (fragmentBytesList == null) { return; } for (int i = 0; i < fragmentBytesList.Count; ++i) { byte[] fragmentBytes = fragmentBytesList[i]; int offset = m_RemoteFileMetadata.GetFileFragmentMemoryOffset(fragmentMetadata) + (int)fragmentMetadata.GetDownloadedBytes(); int length = fragmentBytes.Length; Debug.Log("Copying " + length + " bytes at offset " + offset); CopyDownloadedFragment(offset, length, ref fragmentBytes); fragmentMetadata.AddDownloadedBytes(length); Interlocked.Add(ref mDownloadedContentSize, length); Debug.Log("Downloaded content size: " + mDownloadedContentSize + " / " + mContentSize); } fragmentMetadata.ProcessGetResponse(response); } lastDownloadedURI = request.Uri.AbsoluteUri; // for error checking }
/// <summary> /// Called when: /// -At least one StreamFragmentSize sized fragment downloaded /// -An error occured /// -Download/streaming finished /// </summary> void OnfragmentDownloaded(HTTPRequest req, HTTPResponse resp) { if (resp == null) { Debug.LogError("Download Failed!"); return; } // If streaming is used, then every time this callback function called we can use this function to // retrive the downloaded and buffered data. The returned list can be null, if there is no data yet. List <byte[]> downloadedFragments = resp.GetStreamedFragments(); if (downloadedFragments != null) { Debug.Log("Buffer size: " + downloadedFragments.Count); // First time setup: if (clip == null) { // read wave header data dataPos = ReadWavData(downloadedFragments[0]); // create a new audioclip GetComponent <UnityEngine.AudioSource>().clip = clip = AudioClip.Create("Streamed Clip", frames, 1, bytesPerSec, false #if !UNITY_5_0 , false #endif ); GetComponent <UnityEngine.AudioSource>().loop = false; // no audio samples added yet to our clip samplePos = 0; } // feed our audio clip with the newly arrived data FeedAudio(downloadedFragments); } if (resp.IsStreamingFinished) { Debug.Log("Download Finished!"); } }
/// <summary> /// 保存下载的数据到本地 /// </summary> /// <param name="response"></param> private void SaveZipToLocal(HTTPResponse response) { ProcessFragments(response.GetStreamedFragments()); if (response.IsStreamingFinished) { Debug.Log("zip资源获得成功"); string newPath = PathHelp.GetDownLoadPath() + "data.zip"; if (File.Exists(tempPath)) { if (File.Exists(newPath)) { File.Delete(newPath); } File.Move(tempPath, newPath); File.Delete(tempPath); } Zip.UnZip(newPath, PathHelp.GetDownLoadPath() + PathHelp.unZip); Debug.Log("解压完成"); RequestZipNext(); } }
void OnLeaderboardArrived(HTTPRequest req, HTTPResponse resp) { this.response = resp; if (resp == null) { Debug.LogError(string.Format("{0}: {1}", req.Exception.Message, req.Exception.StackTrace)); return; } List <byte[]> downloadedFragments = resp.GetStreamedFragments(); if (downloadedFragments != null) { foreach (var buffer in downloadedFragments) { downloaded += System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length); } ProcessDownloaded(); } }
void OnDownloadFile(HTTPRequest request, HTTPResponse response) { switch (request.State) { // The request is currently processed. With UseStreaming == true, we can get the streamed fragments here case HTTPRequestStates.Processing: // Set the DownloadLength, so we can display the progress if (downloadLength == 0) { string value = response.GetFirstHeaderValue("content-length"); if (!string.IsNullOrEmpty(value)) { downloadLength = int.Parse(value); } } // Get the fragments, and save them ProcessFragments(request, response.GetStreamedFragments()); break; // The request finished without any problem. case HTTPRequestStates.Finished: if (response.IsSuccess) { if (downloadLength == 0) { string value = response.GetFirstHeaderValue("content-length"); if (!string.IsNullOrEmpty(value)) { downloadLength = int.Parse(value); } } // Save any remaining fragments ProcessFragments(request, response.GetStreamedFragments()); // Completly finished if (response.IsStreamingFinished) { request = null; finishDownload(0, null); } else { Debug.Log("Processing - continue"); } } else { status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", response.StatusCode, response.Message, response.DataAsText); Debug.LogError(status); request = null; finishDownload(-1, status); } break; // The request finished with an unexpected error. The request's Exception property may contain more info about the error. case HTTPRequestStates.Error: status = "Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception"); Debug.LogError(status); request = null; finishDownload(-1, status); break; // The request aborted, initiated by the user. case HTTPRequestStates.Aborted: status = "Request Aborted!"; request = null; finishDownload(-1, status); break; // Ceonnecting to the server is timed out. case HTTPRequestStates.ConnectionTimedOut: status = "Connection Timed Out!"; Debug.LogError(status); request = null; finishDownload(-1, status); break; // The request didn't finished in the given time. case HTTPRequestStates.TimedOut: status = "Processing the request Timed Out!"; Debug.LogError(status); request = null; finishDownload(-1, status); break; } }
public void OnRequest(HTTPRequest req, HTTPResponse resp) { if (req != null && resp != null) { List <byte[]> fragments = resp.GetStreamedFragments(); loc.EnterWriteLock(); if (fragments != null) { for (int i = 0; i < fragments.Count; i++) { byte[] data = fragments[i]; fileStream.Write(data, 0, data.Length); fileStream.Flush(); } } loc.ExitWriteLock(); } switch (req.State) { case HTTPRequestStates.Initial: break; case HTTPRequestStates.Queued: break; case HTTPRequestStates.Processing: break; case HTTPRequestStates.Finished: Clear(false); complete(); break; case HTTPRequestStates.Error: Clear(true); error(req.State.ToString()); break; case HTTPRequestStates.Aborted: break; case HTTPRequestStates.ConnectionTimedOut: Clear(true); error(req.State.ToString()); break; case HTTPRequestStates.TimedOut: Clear(true); error(req.State.ToString()); break; default: break; } /* * if (req.State != HTTPRequestStates.Processing) * { * HFLog.L("下载状态 " + req.State); * } */ }
private void ReadHttpStream(HTTPRequest request, HTTPResponse response) { string localfile = this.m_DownloadInfo.tempPath; try { List <byte[]> streamedFragments = response.GetStreamedFragments(); if (streamedFragments != null) { int num = 0; using (FileStream fileStream = new FileStream(localfile, FileMode.Append)) { foreach (byte[] array in streamedFragments) { num += array.Length; fileStream.Write(array, 0, array.Length); } } this.m_DownloadInfo.downloadedSize += num; } } catch (Exception ex) { Debug.LogErrorFormat("An error occured while downloading {0} due to {1}.Cancelling!", localfile, ex); this.m_DownloadInfo.result = DownloadResult.Failed; //EventManager.Instance.Trigger<SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "failure", this.m_DownloadInfo.downloadedSize).Trigger(); CancelDownload(true); this.CancelDownload(true); return; } float num2 = (float)this.m_DownloadInfo.downloadedSize / (float)this.m_DownloadInfo.downloadSize; this.m_DownloadInfo.currProgress = num2; Debug.LogFormat("Downloading {0} Status: Range {1}/{2} ({3:0.00})", this.m_DownloadInfo.fileName, this.m_DownloadInfo.downloadedSize, this.m_DownloadInfo.downloadSize, this.m_DownloadInfo.currProgress); if (!response.IsStreamingFinished || request.State != HTTPRequestStates.Finished) { return; } Debug.LogFormat("Download finished : {0}", this.m_DownloadInfo.savePath); this.m_DownloadInfo.currProgress = 1.0f; // 续传完成后,做一手MD5验证 string localMd5 = AssetUtils.BuildFileMd5(localfile); if (localMd5.Trim() != m_DownloadInfo.fileMd5.Trim()) { //md5验证失败,删除临时文件 if (File.Exists(localfile)) { File.Delete(localfile); } Debug.LogError("md5 error, retry download:" + localfile + " =>" + localMd5 + " ## " + m_DownloadInfo.fileMd5); this.m_DownloadInfo.result = DownloadResult.Md5Error; this.m_DownloadInfo.currProgress = 0.0f; CancelDownload(true); } else {// md5验证通过,临时文件转为最终文件 string localfile2 = m_DownloadInfo.savePath; if (File.Exists(localfile2)) { File.Delete(localfile2); } File.Move(localfile, localfile2); this.m_DownloadInfo.result = DownloadResult.Success; DownloadManager.Instance.FinishDownloadTask(this.m_DownloadInfo); } //EventManager.Instance.Trigger<SDKEvents.DownloadFileEvent>().Data(this.m_DownloadInfo.fileName, "finish", m_DownloadInfo.downloadedSize).Trigger(); }
/* * void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) * { * GameLooper.BackToMainThread(delegate () * { * float progressPercent = e.ProgressPercentage / 100.0f; * float allProgress = (currentTaskIndex + 0.0f) / taskCount + progressPercent / taskCount; * if (allProgress != 1) * { * progress(allProgress); * } * }); * } * * void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs e) * { * GameLooper.BackToMainThread(delegate () * { * simpleTaskFinish(currentTaskName); * }); * } */ public void OnRequest(HTTPRequest req, HTTPResponse resp) { if (req != null && resp != null) { List <byte[]> fragments = resp.GetStreamedFragments(); writeLock.EnterWriteLock(); using (FileStream fs = new FileStream(currentPath.localPath, FileMode.Append)) { if (fs != null && fragments != null) { foreach (byte[] data in fragments) { fs.Write(data, 0, data.Length); } } } writeLock.ExitWriteLock(); if (resp.IsStreamingFinished) { if (simpleTaskFinish != null) { simpleTaskFinish(currentTaskName); } } } switch (req.State) { case HTTPRequestStates.Initial: break; case HTTPRequestStates.Queued: break; case HTTPRequestStates.Processing: break; case HTTPRequestStates.Finished: break; case HTTPRequestStates.Error: DownLoadManager.Instance.currentDownLoadCount--; fail(req.State.ToString()); break; case HTTPRequestStates.Aborted: DownLoadManager.Instance.currentDownLoadCount--; fail(req.State.ToString()); break; case HTTPRequestStates.ConnectionTimedOut: DownLoadManager.Instance.currentDownLoadCount--; fail(req.State.ToString()); break; case HTTPRequestStates.TimedOut: DownLoadManager.Instance.currentDownLoadCount--; fail(req.State.ToString()); break; default: break; } /* * if (req.State != HTTPRequestStates.Processing) * { * HFLog.L("下载状态 " + req.State); * } */ }