obsidian/笔记文件/2.笔记/Task读取服务器文本和下载文件 解压文件 示例.md
2025-03-26 00:02:56 +08:00

5.7 KiB
Raw Blame History

#unity/代码缓存

SDKEditor

using UnityEngine.Networking;  
using UnityEditor;  
using UnityEngine;  
using System.Threading.Tasks;  
using System.IO;  
using System.IO.Compression;  
  
public class SDKEditor : EditorWindow  
{  
    private static SDKEditor _sdkEditor;  
    private string fileUrl = "http://192.168.2.154/XPackage_Data/XPackage/XPackageConfig_Main.txt";  
    private string folderUrl = "http://192.168.2.154/XPackage_Data/XPackage/Library/LiteHTTP.zip"; //服务器文件  
    private string savePath = "Assets/DownloadedFiles/LiteHTTP.zip"; //保存本地文件  
    private string extractPath = "Assets/DownloadedFiles/Extracted";  // 解压到的目标文件夹路径  
    
    [MenuItem("SDK/SDK编辑器",false)]  
    public static void ShowSDKEditorWindow()  
    {        
        _sdkEditor = (SDKEditor)GetWindowWithRect(typeof(SDKEditor),new Rect(0,0,550,820),false,"SDK编辑器");  
        _sdkEditor.Show();  
    }  
    // 使用 Task 封装 UnityWebRequest 发送请求  
    private async Task<string> SendWebRequestAsync(string url)  
    {        
        // 创建 UnityWebRequest        
        using (UnityWebRequest request = UnityWebRequest.Get(url))  
        {            
            // 使用 TaskCompletionSource 来将 WebRequest 异步化  
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();  
  
            // 开始发送请求  
            request.SendWebRequest().completed += (asyncOp) =>  
            {  
                if (request.result == UnityWebRequest.Result.Success)  
                {                   
                     // 请求成功,将响应内容返回给 Task                    
                     tcs.SetResult(request.downloadHandler.text);  
                }  
                else  
                {  
                    // 请求失败,将错误信息返回给 Task                    
                    tcs.SetException(new System.Exception(request.error));  
                }  
            };  
  
            // 等待请求完成  
            return await tcs.Task;  
        }  
    }  
    private async Task GetPackageInfo()  
    {        
        string response = await SendWebRequestAsync(fileUrl);  
        Debug.Log(response);  // 输出请求响应  
    }  
  
    private async Task DownLoadFile()  
    {        
        DownloadFileAsync(folderUrl, savePath);  
    }  
          
    // 使用 Task 封装 UnityWebRequest 来异步下载文件  
    private async Task DownloadFileAsync(string url, string savePath)  
    {        
        // 创建 UnityWebRequest 下载文件  
        using (UnityWebRequest request = UnityWebRequest.Get(url))  
        {            
            // 使用 TaskCompletionSource 来异步化 WebRequest            
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();  
  
            // 下载完成时的回调  
            request.SendWebRequest().completed += (asyncOp) =>  
            {  
                if (request.result == UnityWebRequest.Result.Success)  
                {                    
                    // 请求成功,保存文件  
                    SaveFile(request.downloadHandler.data, savePath);  
                    tcs.SetResult("Download successful");  
                    StartExtractZip();  
                }  
                else  
                {  
                    // 请求失败,返回错误信息  
                    tcs.SetException(new System.Exception(request.error));  
                }  
            };  
  
            // 等待任务完成并返回结果  
            await tcs.Task;  
        }  
    }  
    // 将下载的文件数据保存到本地  
    private void SaveFile(byte[] data, string path)  
    {        
        try  
        {  
            // 确保目录存在  
            string directory = Path.GetDirectoryName(path);  
            if (!Directory.Exists(directory))  
            {                
                Directory.CreateDirectory(directory);  
            }  
  
            // 将文件数据写入本地文件  
            File.WriteAllBytes(path, data);  
            Debug.Log($"File saved to {path}");  
        }  
        catch (System.Exception ex)  
        {            
            Debug.LogError($"Error saving file: {ex.Message}");  
        }  
    }    
    public async void StartExtractZip()  
    {        
        // 启动解压任务  
        await ExtractZipAsync(savePath, extractPath);  
    }  
  
    // 异步解压 .zip 文件  
    private async Task ExtractZipAsync(string zipFilePath, string extractPath)  
    {        
        // 确保目标文件夹存在  
        if (!Directory.Exists(extractPath))  
        {            
            Directory.CreateDirectory(extractPath);  
        }  
  
        // 将解压过程放到后台线程进行  
        await Task.Run(() => ExtractZip(zipFilePath, extractPath));  
  
        // 完成后切回主线程Unity的主线程  
        Debug.Log("Extract completed! Now back to main thread.");  
        AssetDatabase.Refresh();  
    }  
  
    // 负责解压文件的同步方法  
    private void ExtractZip(string zipFilePath, string extractPath)  
    {        
        try  
        {  
            // 解压 .zip 文件  
            ZipFile.ExtractToDirectory(zipFilePath, extractPath);  
            Debug.Log($"File extracted to {extractPath}");  
        }  
        catch (System.Exception ex)  
        {            Debug.LogError($"Error extracting zip file: {ex.Message}");  
        }  
    }          
  
    private void OnGUI()  
    {        
        if (GUILayout.Button("Add", GUILayout.Width(100)))  
        {            
            GetPackageInfo();  
            DownLoadFile();  
        }  
    }
}