迅雷下载(断点续传)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.IO;

using System.Net;
using System;

public class DownLoadManager : MonoBehaviour
{
    #region Member variable area
    public static DownLoadManager Instance;
    private Queue<DownLoadTask> downLoadQueue;
    private bool isAllDownloadFinish = true;
    private List<DownLoadTask> taskList;

    private GameObject taskTemplate;
    private ScrollRect taskScrollView;
    private List<GameObject> taskGOList;

    private ushort downLoadFinishCount;
    #endregion

    private void Awake()
    {
        Instance = this;
        downLoadQueue = new Queue<DownLoadTask>();
        taskList = new List<DownLoadTask>();

        taskScrollView = GameObject.Find("Scroll View").GetComponent<ScrollRect>();
        taskTemplate = taskScrollView.transform.Find("Viewport/Content/DownloadTaskTemplate").gameObject;
        taskTemplate.SetActive(false);
        taskGOList = new List<GameObject>();
    }

    public void AddDownLoadTask(DownLoadTask task)
    {
        downLoadQueue.Enqueue(task);
        if (downLoadQueue.Count >= 1 && isAllDownloadFinish)
        {
            StartCoroutine(DownLoad());
        }
    }

    IEnumerator DownLoad()
    {
        isAllDownloadFinish = false;
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();
        Debug.Log(downLoadQueue.Count);
        while (downLoadQueue.Count > 0)
        {
            DownLoadTask task = downLoadQueue.Dequeue();
            taskList.Add(task);
            GameObject taskGO = GameObject.Instantiate<GameObject>(taskTemplate);
            taskGO.SetActive(true);
            taskGO.transform.SetParent(taskTemplate.transform.parent);
            taskGOList.Add(taskGO);
            Debug.Log(task.fileName);
            //yield return task.DownLoad();
            StartCoroutine(task.DownLoad());
            yield return null;
        }
        stopWatch.Stop();
        Debug.Log("总耗时:" + stopWatch.ElapsedMilliseconds * 0.001 + "秒");
        isAllDownloadFinish = true;
    }

    private void RefreshTaskView()
    {
        if (taskGOList.Count > 0 && downLoadFinishCount < taskGOList.Count)
        {
            downLoadFinishCount = 0;
            for (int i = 0; i < taskGOList.Count; i++)
            {
                Text fileName = taskGOList[i].transform.Find("Background/FileName").GetComponent<Text>();
                Text internetSpeed = taskGOList[i].transform.Find("Background/InternetSpeed").GetComponent<Text>();
                RectTransform fg = taskGOList[i].transform.Find("Background/ImgProgress_BG/FG").GetComponent<RectTransform>();
                Text progress = taskGOList[i].transform.Find("Background/ImgProgress_BG/FG/Progress").GetComponent<Text>();

                DownLoadTask task = taskList[i];
                fileName.text = task.fileName;
                bool requestIsNull = task.request == null || task.isHad;
                internetSpeed.text = requestIsNull ? string.Empty : (task.request.isDone ? string.Empty : (task.request.downloadedBytes / 1024) + "k");
                fg.sizeDelta = new Vector2(requestIsNull ? 600 : task.request.downloadProgress * 600, fg.sizeDelta.y);
                progress.text = requestIsNull ? "已完成" : Mathf.RoundToInt(task.request.downloadProgress * 100) + "%";
                if (task.request != null && task.request.isDone || task.isHad)
                {
                    ++downLoadFinishCount;
                }
            }
        }
    }

    private void Update()
    {
        RefreshTaskView();
    }

    private void OnApplicationQuit()
    {
        for (int i = 0; i < taskList.Count; i++)
        {
            if (taskList[i].request != null)
            {
                taskList[i].request.Dispose();
            }
        }
        StopAllCoroutines();
    }
}

/// <summary>下载任务</summary>
public class DownLoadTask
{
    public string fileName = string.Empty;
    public DownLoadTask(string fileName)
    {
        this.fileName = fileName;
    }

    public UnityWebRequest request;
    public bool isHad = false;

    public virtual void DownLoadBegin() { }
    public virtual void DownLoadEnd() { }
    public virtual void DownLoadError() { }

    public IEnumerator DownLoad()
    {
        #region UnityWebRequest.Head()有局限性,故废弃
        //DownLoadBegin();
        //UnityWebRequest headRequest = UnityWebRequest.Head(Path.Combine(ConfigInfo.assetServerPath, fileName));
        //Debug.Log("Start send web request");
        //yield return headRequest.SendWebRequest();
        //Debug.Log("End send web request");
        //if (!string.IsNullOrEmpty(headRequest.error))
        //{
        //    Debug.Log("获取文件大小失败");
        //    yield break;
        //}
        //long totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));
        //headRequest.Dispose();
        #endregion

        long totalLength = GetLength(Path.Combine(ConfigInfo.assetServerPath, fileName));
        string fileFullPath = Path.Combine(ConfigInfo.savePath, fileName);
        if (!Directory.Exists(ConfigInfo.savePath))
        {
            Directory.CreateDirectory(ConfigInfo.savePath);
        }
        FileStream fs = new FileStream(fileFullPath, FileMode.OpenOrCreate);
        long fileLength = fs.Length;
        fs.Dispose();

        request = new UnityWebRequest(Path.Combine(ConfigInfo.assetServerPath, fileName));
        isHad = fileLength >= totalLength;
        if (fileLength < totalLength)
        {
            DownLoadBegin();

            request.downloadHandler = new DownloadHandlerFile(fileFullPath, true);
            request.SetRequestHeader("Range", "bytes=" + fileLength + "-");

            request.SendWebRequest();
            while (!request.isDone)
            {
                //Debug.LogFormat("下载大小:{0}k/{1}k 进度:{2}%", (long)request.downloadedBytes / 1024 + fileLength, totalLength / 1024,
                    //request.downloadProgress * 100);
                //Debug.Log("当前下载大小:" + request.downloadedBytes / 1024 + "k");
                yield return null;
            }
            if (!string.IsNullOrEmpty(request.error))
            {
                Debug.Log("下载失败");
                DownLoadError();
                yield break;
            }
        }

        DownLoadEnd();
    }


    /// <summary>获取下载文件的大小</summary>
    long GetLength(string url)
    {
        HttpWebRequest requet = HttpWebRequest.Create(url) as HttpWebRequest;
        requet.Method = "HEAD";
        HttpWebResponse response = requet.GetResponse() as HttpWebResponse;
        return response.ContentLength;
    }
}

public class ConfigInfo
{
    public static readonly string assetServerPath = "http://192.168.10.49/android/trunk";
    //public static readonly string assetServerPath = "http://xrlmall.top/PuzzleHero";
    public static readonly string savePath = Path.Combine(Application.streamingAssetsPath, "DownloadAsset");
    public static readonly int downloadTimeout = 5000;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UseDownload : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            DownLoadTask task = new DownLoadTask("hotLib_x86.zip");
            DownLoadManager.Instance.AddDownLoadTask(task);
            DownLoadTask task2 = new DownLoadTask("hotLib.zip");
            DownLoadManager.Instance.AddDownLoadTask(task2);
            DownLoadTask task3 = new DownLoadTask("assets.zip");
            DownLoadManager.Instance.AddDownLoadTask(task3);

            //DownLoadTask task3 = new DownLoadTask("PuzzleHero.apk");
            //DownLoadManager.Instance.AddDownLoadTask(task3);

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值