using Cysharp.Threading.Tasks; using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using System.Threading; using UnityEngine; using UnityEngine.Networking; /// /// 下载测试 /// public class DownloadTest { /// /// 下载URL /// private const string DOWNLOAD_URL = "http://1.14.62.163/Build/TapTapDev/Android/0.1.0/OutputCache.manifest"; /// /// 超时时间 /// private readonly double timeOutTick = 10f; // 10秒没下完超时 /// /// 当前下载间隔 /// private float intervals = 15f; /// /// 计时 /// private float timer = 0f; /// /// 总下载次数 /// private int total; private StreamWriter writerUnityWebRequest; private StreamWriter writerHttpClient; /// /// 最大下载次数 /// public int MaxDownloadCount { get; private set; } /// /// 是否开始下载 /// public bool IsBeginDownload { get; private set; } public DownloadTest() { IsBeginDownload = false; } /// /// 开始下载测试 /// public async void BeginDownload() { if (IsBeginDownload) return; IsBeginDownload = true; string fileUnityWebRequestPath = Path.Combine(Application.persistentDataPath, "UnityWebRequestTest.txt"); string fileHttpClientPath = Path.Combine(Application.persistentDataPath, "HttpClientTest.txt"); Debug.Log($"开始下载测试,下载{MaxDownloadCount}次,保存文件路径:{fileUnityWebRequestPath}和{fileHttpClientPath}"); timer = intervals; total = 0; MaxDownloadCount = 5; writerUnityWebRequest = File.CreateText(fileUnityWebRequestPath); writerHttpClient = File.CreateText(fileHttpClientPath); while (IsBeginDownload) { if (timer >= intervals) { timer -= intervals; ++total; if (total > MaxDownloadCount) { StopDownload(); return; } string networdType = Application.internetReachability switch { NetworkReachability.ReachableViaCarrierDataNetwork => "流量", NetworkReachability.ReachableViaLocalAreaNetwork => "Wifi", _ => "没有网络" }; DownloadByUnityWebRequest(networdType); DownloadByHttpClient(networdType); } await UniTask.DelayFrame(1); timer += Time.deltaTime; } } /// /// 停止下载 /// public void StopDownload() { writerUnityWebRequest.Flush(); writerUnityWebRequest.Close(); writerHttpClient.Flush(); writerHttpClient.Close(); IsBeginDownload = false; } /// /// 通过WebRequest下载 /// private async void DownloadByUnityWebRequest(string netword) { string log = string.Empty; DateTime startTime = DateTime.Now; DateTime endTime; using UnityWebRequest request = UnityWebRequest.Get(DOWNLOAD_URL); UnityWebRequestAsyncOperation asyncOperation = request.SendWebRequest(); while (!asyncOperation.isDone) { await UniTask.DelayFrame(1); endTime = DateTime.Now; TimeSpan timeSpan = endTime - startTime; if (timeSpan.TotalSeconds > timeOutTick) { request.Abort(); log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, {timeOutTick}s超时,URL:{DOWNLOAD_URL}"; Debug.LogWarning(log); writerUnityWebRequest.WriteLine(log); writerUnityWebRequest.Flush(); SendWechatMessage(log); return; } } endTime = DateTime.Now; if (request.result != UnityWebRequest.Result.Success) { log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,是否成功:{false},URL:{DOWNLOAD_URL}"; Debug.LogError(log); writerUnityWebRequest.WriteLine(log); writerUnityWebRequest.Flush(); SendWechatMessage(log); return; } log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,是否成功:{true},URL:{DOWNLOAD_URL}"; Debug.Log(log); writerUnityWebRequest.WriteLine(log); writerUnityWebRequest.Flush(); } /// /// 通过HttpClient下载 /// private async void DownloadByHttpClient(string netword) { string log = string.Empty; DateTime startTime = DateTime.Now; DateTime endTime; CancellationTokenSource cancellationTokenSource = new(); using HttpClient client = new(); Task response = client.GetAsync(DOWNLOAD_URL, cancellationTokenSource.Token); while (!response.IsCompleted) { await UniTask.DelayFrame(1); endTime = DateTime.Now; TimeSpan timeSpan = endTime - startTime; if (timeSpan.TotalSeconds > timeOutTick) { cancellationTokenSource.Cancel(); log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, {timeOutTick}s超时,URL:{DOWNLOAD_URL}"; Debug.LogWarning(log); writerHttpClient.WriteLine(log); writerHttpClient.Flush(); SendWechatMessage(log); return; } } endTime = DateTime.Now; if (!response.IsCompletedSuccessfully || !response.Result.IsSuccessStatusCode) { log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,是否成功:{false},URL:{DOWNLOAD_URL}"; Debug.LogError(log); writerHttpClient.WriteLine(log); writerHttpClient.Flush(); SendWechatMessage(log); return; } log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,是否成功:{true},URL:{DOWNLOAD_URL}"; Debug.Log(log); writerHttpClient.WriteLine(log); writerHttpClient.Flush(); } /// /// 发送企业微信通知 /// public async void SendWechatMessage(string content) { string url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bf89f555-f710-48c4-87d0-7a8182dec13e"; string message = "{\r\n" + "\"msgtype\":\"text\",\r\n" + "\"text\":{\r\n" + $"\"content\":\"{content}\",\r\n" + $"\"mentioned_list\":[\"@all\"]" + "}\r\n" + "}"; UnityWebRequest request = UnityWebRequest.Post(url, message, "application/json"); await request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) Debug.LogError($"Error: {request.error}"); else Debug.Log($"Response: {request.downloadHandler.text}"); // 请求成功,输出响应数据 request.Dispose(); } }