Esempio n. 1
0
    void Update()
    {
        if (downloadList == null)
        {
            return;
        }

        if (canDownload)
        {
            while (downloadList.Count > 0)
            {
                DownloadUnit item = downloadList [0];
                if (table.ContainsKey(item.addr))
                {
                    downloadList.RemoveAt(0);
                    SetImageBase(item.t, item.addr);
                }
                else
                {
                    canDownload = false;
                    StartCoroutine(GetTexture(item.addr));
                    break;
                }
            }
        }
    }
Esempio n. 2
0
    /// <summary>
    /// 异步会创建线程
    /// </summary>
    /// <param name="info"></param>
    public void DownloadAsync(DownloadUnit info)
    {
        if (info == null)
        {
            return;
        }

        var fileMac = new DownloadFileMac(info);

        lock (mlock)
        {
            readyList.Enqueue(fileMac);
        }

        if (runningList.Count < MAX_THREAD_COUNT)
        {
            var thread = new Thread(ThreadLoop);

            lock (mlock)
            {
                runningList.Add(thread, null);
            }

            thread.Start();
        }
    }
 public void StartProcess()
 {
     if (_currentUnitIndex >= _downloadUnints.Length)
     {
         ProcessFinished?.Invoke(new DownloadProcessControlEventArgs
         {
             Message = $"BIN文件全部下载结束,共{TotalFileDownloadMissions}个文件,成功下载{CurrentFileIndex}个文件。"
         });
         return;
     }
     _onProcessUnit = _downloadUnints[_currentUnitIndex];
     _onProcessUnit.DownloadInterrupted += (e) =>
     {
         if (_currentUnitIndex >= _downloadUnints.Length)
         {
             ProcessInterrupted?.Invoke(new DownloadProcessControlEventArgs
             {
                 Message   = e.Message,
                 Exception = e.Exception
             });
         }
         else
         {
             ProcessSkiped?.Invoke(new DownloadProcessControlEventArgs
             {
                 Message   = "文件下载出错,下载已跳过,继续处理后续设备下载。",
                 Exception = e.Exception
             });
             StartProcess();
         }
     };
     _onProcessUnit.DownloadFinished += (e) => StartProcess();
     _onProcessUnit.StartDownload();
     _currentUnitIndex++;
 }
Esempio n. 4
0
 /// <summary>
 /// 删除下载
 /// </summary>
 /// <param name="info"></param>
 public void DeleteDownload(DownloadUnit info)
 {
     lock (mlock)
     {
         info.IsDelete = true;
     }
 }
        void Update()
        {
            lock (m_lock_obj)
            {
                if (m_downloading.Count > 0)
                {
                    // Loger.d("下载状态更新 下载中:"+m_downloading.Count);
                    m_removeKeys.Clear();
                    foreach (var kv in m_downloading)
                    {
                        if (kv.Value.IsDone)
                        {
                            m_removeKeys.Add(kv.Key);
                        }
                    }
                    // Loger.d("下载状态更新 下载结束:"+m_removeKeys.Count);
                    for (int i = 0; i < m_removeKeys.Count; i++)
                    {
                        DownloadUnit state = m_downloading[m_removeKeys[i]];

                        Loger.d("[MultiThreadDownload.Update]:{0} {1}", state.IsSucc, state.Url);
                        m_downloading.Remove(m_removeKeys[i]);
                        if (state.Callback != null)
                        {
                            state.Callback(state.IsSucc);
                        }
                        downloadQueueReset();
                    }
                }
            }
        }
Esempio n. 6
0
    /// <summary>
    /// 同步不会调用回调函数,返回是否成功
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public bool DownloadSync(DownloadUnit info)
    {
        if (info == null)
        {
            return(false);
        }

        var mac = new DownloadFileMac(info);

        try // 同步下载尝试三次
        {
            mac.Run();
            if (mac.State == DownloadMacState.Complete)
            {
                return(true);
            }
            mac.Run();
            if (mac.State == DownloadMacState.Complete)
            {
                return(true);
            }
            mac.Run();
            if (mac.State == DownloadMacState.Complete)
            {
                return(true);
            }
        }
        catch (Exception ex)
        {
            Debug.Log("Error DownloadSync " + mac.State + " " + mac.DownUnit.Name + " " + ex.Message + " " + ex.StackTrace);
        }

        return(false);
    }
Esempio n. 7
0
    /// <summary>
    /// 下载版本文件列表
    /// </summary>
    private void DownloadVersionFile()
    {
        allDownloadSize = 0;

        currentState = HotFix_ProjectState.DownloadVersionFile;

        var versionListServerFile = GPath.PersistentAssetsPath + serverVersion.ToString() + ".txt";

        if (File.Exists(versionListServerFile))
        {
            File.Delete(versionListServerFile);
        }

        var versionListUnit = new DownloadUnit()
        {
            Name     = serverVersion.ToString() + ".txt",
            SavePath = versionListServerFile,
            DownUrl  = GPath.CDNUrl + serverVersion.ToString() + ".txt",
        };

        versionListUnit.ErrorFun = (DownloadUnit downUnit, string msg) =>
        {
            Debug.LogWarning("CompareVersion Download Error " + msg + "\n" + downUnit.DownUrl);
            downloadMgr.DeleteDownload(versionListUnit);
            UpdateError();
        };

        versionListUnit.CompleteFun = (DownloadUnit downUnit) =>
        {
            if (!File.Exists(versionListServerFile)) // 文件不存在,重新下载
            {
                UpdateError();
                return;
            }

            fileVersionMgr.InitVersionFile(versionListServerFile);

            var updateList = fileVersionMgr.FindUpdateFiles(clientVersion.Version);

            allDownloadSize = fileVersionMgr.DownloadSize;

            Debug.Log("版本文件数量:" + updateList.Count);

            if (updateList.Count > 0)
            {
                StartDownloadList(updateList);
            }

            else
            {
                SaveVersion();
            }
        };

        downloadMgr.DownloadAsync(versionListUnit);

        Debug.Log("版本文件url:" + versionListUnit.DownUrl);
    }
 void downloadQueueReset()
 {
     while (m_downloading.Count < Config.MAX_DOWNLOAD_COUNT && m_downloadQueue.Count > 0)
     {
         DownloadUnit item = m_downloadQueue[0];
         m_downloadQueue.RemoveAt(0);
         string key = getKey(item.Url, item.SavePath);
         m_downloading[key] = item;
         downloadAsyn(item);
     }
 }
        public DownloadProcessControl(BinInfo[] binfileInfos, List <IDownloadSender> downloadSenders)
        {
            TotalFileDownloadMissions = binfileInfos.Length * downloadSenders.Count;
            _downloadUnints           = new DownloadUnit[downloadSenders.Count];
            var index = 0;

            foreach (var currentDownloadSender in downloadSenders)
            {
                _downloadUnints[index] = new DownloadUnit(binfileInfos, currentDownloadSender);
                index++;
            }
        }
Esempio n. 10
0
        /*--- Method: Initialization ----------------------------------------------------------------------------------------------------------------------------------*/

        /// <summary> オブジェクトモデルの初期化を実行します。
        /// </summary>
        /// <returns> 正常終了時 True </returns>
        private bool initObjectModel()
        {
            this.NewPluginVersionInfo = new PluginVersionInfo();
            this.UpdateStatusData     = new UpdateStatusData();

            this.downloadUnit         = new DownloadUnit();
            this.xmlSerializerProcess = new XmlSerializerProcess();
            this.NewPlugin            = false;

            this.DialogOpenFLG = false;
            this.UpdateClose   = false;
            return(true);
        }
        /*--- Method: Initialization ----------------------------------------------------------------------------------------------------------------------------------*/

        /// <summary> モジュールの初期化を実行します。
        /// </summary>
        /// <returns> 正常終了時 True </returns>
        private bool initModule()
        {
            this.downloadUnit = new DownloadUnit();

            this.overlayViewOpenProcess     = new OverlayViewOpenProcess();
            this.xmlSerializerProcess       = new XmlSerializerProcess();
            this.setFilterProcess           = new SetFilterProcess();
            this.appDataFileManageProcess   = new AppDataFileManageProcess();
            this.saveChangedResetProcess    = new SaveChangedResetProcess();
            this.ovarlayDefaultSetProcess   = new OvarlayDefaultSetProcess();
            this.overlayDataRevisionProcess = new OverlayDataRevisionProcess();

            return(true);
        }
Esempio n. 12
0
        private void Download()
        {
            if (DownloadIndex == DownloadQueue.Count)
            {
                saveButton.Enabled  = true;
                saveButton.Progress = 0;
                saveButton.Text     = Language.GetString("PerformButton");
                DownloadQueue.Clear();
                return;
            }
            DownloadUnit du = DownloadQueue[DownloadIndex];

            Client = new WebClient();
            Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
            Client.DownloadFileCompleted   += new AsyncCompletedEventHandler(DownloadProgressCompleted);
            Client.DownloadFileAsync(du.Url, du.File);
        }
        void downloadAsyn(DownloadUnit _unit)
        {
            if (Directory.Exists(Path.GetDirectoryName(_unit.SavePath)))
            {
                if (File.Exists(_unit.SavePath))
                {
                    try
                    {
                        File.Delete(_unit.SavePath);
                    }
                    catch (Exception _e)
                    {
                        err("[MultiThreadDownload.downloadAsyn]:一个(存在)却删不掉的文件,{0}\n{1}", _e.Message, _unit.SavePath);
                        downloadingResult(false, null, getKey(_unit.Url, _unit.SavePath));
                        return;
                    }
                }
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(_unit.SavePath));
                }
                catch (Exception _e)
                {
                    err("[MultiThreadDownload.downloadAsyn]:创建文件夹失败,{0}\n{1}", _e.Message, _unit.SavePath);
                    downloadingResult(false, null, getKey(_unit.Url, _unit.SavePath));
                    return;
                }
            }
            WebClient client = new WebClient();

            m_client2Keys[client]         = getKey(_unit.Url, _unit.SavePath);
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(downloadFileCompleted);
            try
            {
                client.DownloadFileAsync(new Uri(_unit.Url), _unit.SavePath + Config.TEMP_EXTENSION);
            }
            catch (System.Exception _e)
            {
                err(_e.Message);
                downloadingResult(false, client);
            }
        }
Esempio n. 14
0
        private void DownloadProgressCompleted(object sender, AsyncCompletedEventArgs e)
        {
            DownloadUnit du = DownloadQueue[DownloadIndex];

            if (e.Cancelled)
            {
                if (File.Exists(du.File))
                {
                    File.Delete(du.File);
                }
                return;
            }
            TreeNode tn = this.engineTree.Nodes[du.EngineIndex].Nodes[du.VersionIndex];

            tn.Text = tn.Text.Replace(Language.GetString("NotDownloaded"), Language.GetString("Downloaded"));
            DownloadIndex++;
            Download();
        }
        public void Download(string _url, string _savePath, Action <bool> _callback)
        {
            Loger.d("[MultiThreadDownload.Download]:{0}\n{1}\n{2}", _url, _savePath, _callback);

            if (string.IsNullOrEmpty(_url))
            {
                err("[MultiThreadDownload.Download]下载地址不能为空:{0}", _url);
                _callback(false);
                return;
            }
            if (string.IsNullOrEmpty(_savePath))
            {
                err("[MultiThreadDownload.Download]存储地址不能为空:{0}", _savePath);
                _callback(false);
                return;
            }

            lock (m_lock_obj)
            {
                string key = getKey(_url, _savePath);
                if (m_downloading.ContainsKey(key))
                {
                    m_downloading[key].Callback += _callback;
                }
                else
                {
                    var unit = m_downloadQueue.Find((_unit) => { return(_unit.Url == _url && _unit.SavePath == _savePath); });
                    if (unit != null)
                    {
                        unit.Callback += _callback;
                    }
                    else
                    {
                        DownloadUnit state = new DownloadUnit();
                        state.Url       = _url;
                        state.SavePath  = _savePath;
                        state.Callback += _callback;
                        m_downloadQueue.Add(state);
                        downloadQueueReset();
                    }
                }
            }
            // UnityWebDownload.Instance.Download(_url,_savaPath,_callback);
        }
Esempio n. 16
0
    /// <summary>
    /// 单个下载
    /// 开线程
    /// </summary>
    /// <param name="downUnit"></param>
    /// <param name="precentCallback">下载进度回调</param>
    public void SingleDownload(DownloadUnit downUnit, System.Action <long, long, bool> callback, System.Action <DownloadUnit> errorCallback = null)
    {
        if (File.Exists(downUnit.FullPath))
        {
            if (callback != null)
            {
                callback(1, 1, true);
            }
            return;
        }
        EasyThread downloadThread = null;

        downloadThread = new EasyThread(() =>
        {
            download(downUnit, callback, downloadThread, errorCallback);
            downloadThread.Stop();
        });
        downloadThread.Start();
    }
Esempio n. 17
0
    public void SetImage(Transform t, string addr)
    {
        if (table == null)
        {
            return;
        }

        if (table.ContainsKey(addr))
        {
            SetImageBase(t, addr);
        }
        else
        {
            DownloadUnit item = new DownloadUnit();
            item.addr = addr;
            item.t    = t;
            if (downloadList != null)
            {
                downloadList.Add(item);
            }
        }
    }
Esempio n. 18
0
        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="downUnit"></param>
        /// <param name="callback"></param>
        static void download(DownloadUnit downUnit, System.Action <long, long> callback, System.Action <DownloadUnit> errorCallback = null)
        {
            //打开上次下载的文件
            long       startPos = 0;
            string     tempFile = downUnit.savePath + ".temp";
            FileStream fs       = null;

            //如果有该文件则读取文件字节长度 如果不完整,那么从当前长度开始下载
            if (File.Exists(tempFile))
            {
                fs       = File.OpenWrite(tempFile);
                startPos = fs.Length;
                fs.Seek(startPos, SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                //没有就创建
                string direName = Path.GetDirectoryName(tempFile);
                if (!Directory.Exists(direName))
                {
                    Directory.CreateDirectory(direName);
                }
                fs = new FileStream(tempFile, FileMode.Create);
            }

            // 下载逻辑
            HttpWebRequest request = null;
            WebResponse    respone = null;
            Stream         ns      = null;

            try
            {
                request = WebRequest.Create(downUnit.downUrl) as HttpWebRequest;
                request.ReadWriteTimeout = ReadWriteTimeOut;
                request.Timeout          = TimeOutWait;
                if (startPos > 0)
                {
                    request.AddRange((int)startPos);                //设置Range值,断点续传
                }
                //向服务器请求,获得服务器回应数据流
                respone = request.GetResponse();
                ns      = respone.GetResponseStream();
                long totalSize = respone.ContentLength;
                long curSize   = startPos;
                if (curSize == totalSize)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                    if (File.Exists(downUnit.savePath))
                    {
                        File.Delete(downUnit.savePath);
                    }
                    File.Move(tempFile, downUnit.savePath);
                    if (callback != null)
                    {
                        callback(curSize, totalSize);
                    }
                }
                else
                {
                    byte[] bytes    = new byte[oneReadLen];
                    int    readSize = ns.Read(bytes, 0, oneReadLen); // 读取第一份数据
                    while (readSize > 0)
                    {
                        fs.Write(bytes, 0, readSize);       // 将下载到的数据写入临时文件
                        curSize += readSize;

                        // 判断是否下载完成
                        // 下载完成将temp文件,改成正式文件
                        if (curSize == totalSize)
                        {
                            fs.Flush();
                            fs.Close();
                            fs = null;
                            if (File.Exists(downUnit.savePath))
                            {
                                File.Delete(downUnit.savePath);
                            }
                            File.Move(tempFile, downUnit.savePath);
                        }

                        // 回调一下
                        if (callback != null)
                        {
                            callback(curSize, totalSize);
                        }
                        // 往下继续读取
                        readSize = ns.Read(bytes, 0, oneReadLen);
                    }
                }
            }
            catch (WebException ex)
            {
                if (errorCallback != null)
                {
                    errorCallback(downUnit);
                    Debug.Log("下载出错:" + ex.Message);
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }
                if (ns != null)
                {
                    ns.Close();
                }
                if (respone != null)
                {
                    respone.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
        }
Esempio n. 19
0
    /// <summary>
    /// 下载版本资源
    /// </summary>
    /// <param name="updateList"></param>
    private void StartDownloadList(List <FileVersionData> updateList)
    {
        currentState = HotFix_ProjectState.CompareAssetVersion;

        var saveRootPath = GPath.StreamingAssetsPath;
        var urlRootPath  = GPath.CDNUrl;

        var downloadList     = new List <DownloadUnit>();
        var downloadSizeList = new Dictionary <string, int>();
        int downloadCount    = updateList.Count;
        int downloadMaxCount = downloadCount;

        curDownloadArray = new int[downloadCount];

        int existAllSize = 0;
        int totalAllSize = 0;

        int downloadedFileSizes = 0;
        int downloadAllFileSize = 0;

        foreach (var fileData in updateList)
        {
            var savePath = saveRootPath + fileData.Name;
            if (File.Exists(savePath))
            {
                FileInfo fi = new FileInfo(savePath);
                if (fileData.Size == (int)fi.Length)
                {
                    //长度相等,可能是已经下载的
                    //downloadNameList.Add(fileData.Name, fileData.Name);
                    //existAllName += fileData.Name;
                }
                else // 长度不相等,需要重新下载
                {
                    //Utils.Log("StartDownloadList Delete fileData.Size="+ fileData.Size + " fi.Length="+ fi.Length);
                    fi.Delete();
                    downloadSizeList.Add(fileData.Name, 0);
                    totalAllSize += fileData.Size;
                }
            }
            else
            {
                downloadSizeList.Add(fileData.Name, 0);
                totalAllSize += fileData.Size;
            }

            var downloadUnit = new DownloadUnit()
            {
                Name     = fileData.Name,
                DownUrl  = urlRootPath + fileData.Version + "/Assets/" + fileData.Name,
                SavePath = savePath,
                Size     = fileData.Size,
                Md5      = fileData.Md5,
            };

            downloadUnit.ErrorFun = (DownloadUnit downUnit, string msg) =>
            {
                string errorMgs = "StartDownloadList Error " + downUnit.DownUrl + " " + msg + "\n";
                Debug.LogWarning(errorMgs);
            };

            downloadUnit.ProgressFun = (DownloadUnit downUnit, int curSize, int allSize) =>
            {
                curDownloadArray[downloadMaxCount - downloadCount] = curSize;

                if (downloadSizeList.ContainsKey(downUnit.Name))
                {
                    downloadedFileSizes += curSize - downloadSizeList[downUnit.Name];

                    downloadSizeList[downUnit.Name] = curSize;
                }
                else
                {
                    Debug.LogError("downUnit 不存在 = " + downUnit.Name);
                }

                UpdateProgress?.Invoke(DownloadProgress);

                //Debug.LogFormat("正在下载资源:{0},已下载大小:{1},总大小:{2}", downUnit.Name, curSize, allSize);
            };

            downloadUnit.CompleteFun = (DownloadUnit downUnit) =>
            {
                downloadCount--;

                int percent = (downloadMaxCount - downloadCount) * 10 / downloadMaxCount;

                if (downloadCount == 0) // 下载完成
                {
                    SaveVersion();

                    HotFixCallback(HotFix_ProjectState.Finished, "下载完成", null);
                }
            };

            downloadList.Add(downloadUnit);
        }

        downloadedFileSizes = 0;
        downloadAllFileSize = totalAllSize;

        //如果文件都存在,用已下载的作为长度,概率极低,为了表现进度特殊处理
        if (totalAllSize == 0)
        {
            downloadedFileSizes = 1;
            downloadAllFileSize = 1;
        }

        Debug.Log("下载文件总大小:" + totalAllSize);

        Action downloadFun = () =>
        {
            currentState = HotFix_ProjectState.DownloadFiles;
            foreach (var downUnit in downloadList)
            {
                downloadMgr.DownloadAsync(downUnit);
            }
        };

        if (totalAllSize < 1024 * 1024) //<1MB
        {
            downloadFun();
        }
        else
        {
            HotFixCallback(HotFix_ProjectState.RequestDownloadFiles, "游戏需要更新部分资源(" +
                           (totalAllSize / 1024 / 1024) + "M),建议您在无线局域网环境下更新", (run) =>
            {
                if (run == true)
                {
                    downloadFun();
                }
            });
        }
    }
Esempio n. 20
0
    /// <summary>
    /// 下载
    /// </summary>
    /// <param name="downUnit"></param>
    /// <param name="callback"></param>
    private void download(DownloadUnit downUnit, System.Action <long, long, bool> callback, EasyThread downloadThread, System.Action <DownloadUnit> errorCallback = null)
    {
        //打开上次下载的文件
        long startPos = 0;
        //将文件的后缀名改为临时文件名 .temp
        string tempfilename = downUnit.fileName.Replace(Path.GetExtension(downUnit.fileName), ".temp");
        string tempFile     = downUnit.savePath + "/" + tempfilename;
        string InstallFile  = downUnit.savePath + "/" + downUnit.fileName;

        //Debug.LogError("文件路径 :" + InstallFile + "  /文件名称/     :" + downUnit.fileName  + "            /服务器的md5/    :" + downUnit.md5);

        long totalSize = GetWebFileSize(downUnit.downUrl);
        //float totalSize;
        //float.TryParse(downUnit.size, out totalSize);
        //Debug.Log(totalSize);
        FileStream fs = null;

        //若此文件已经存在 则直接返回文件的总大小
        if (File.Exists(InstallFile) && string.Equals(Utility.GetMd5Hash(File.OpenRead(InstallFile)), downUnit.md5))
        {
            //不执行下载流程
            Debug.LogError("下载的文件 已经存在                 : " + InstallFile);
            if (callback != null)
            {
                callback(totalSize, totalSize, true);
            }
            return;
        }
        if (File.Exists(tempFile))
        {
            fs       = File.OpenWrite(tempFile);
            startPos = fs.Length;
            fs.Seek(startPos, SeekOrigin.Current); //移动文件流中的当前指针
        }
        else
        {
            string direName = Path.GetDirectoryName(tempFile);
            if (!Directory.Exists(direName))
            {
                Directory.CreateDirectory(direName);
            }
            fs = new FileStream(tempFile, FileMode.Create);
            Debug.Log(fs.ToString());
        }
        // 下载逻辑
        HttpWebRequest request = null;
        WebResponse    respone = null;
        Stream         ns      = null;

        try
        {
            request = WebRequest.Create(downUnit.downUrl) as HttpWebRequest;
            request.ReadWriteTimeout = ReadWriteTimeOut;
            request.Timeout          = TimeOutWait;
            if (startPos > 0)
            {
                request.AddRange((int)startPos);                //设置Range值,断点续传
            }
            //向服务器请求,获得服务器回应数据流
            respone = request.GetResponse();
            ns      = respone.GetResponseStream();
            long   curSize  = startPos;
            byte[] bytes    = new byte[oneReadLen];
            int    readSize = ns.Read(bytes, 0, oneReadLen); // 读取第一份数据
            while (readSize > 0)
            {
                //如果Unity客户端关闭,停止下载
                if (IsStop)
                {
                    if (fs != null)
                    {
                        fs.Flush();
                        fs.Close();
                        fs = null;
                    }
                    if (ns != null)
                    {
                        ns.Close();
                    }
                    if (respone != null)
                    {
                        respone.Close();
                    }
                    if (request != null)
                    {
                        request.Abort();
                    }

                    downloadThread.Stop();
                }
                fs.Write(bytes, 0, readSize);       // 将下载到的数据写入临时文件
                curSize += readSize;

                // 回调一下
                if (callback != null)
                {
                    callback(curSize, totalSize, false);
                }
                // 往下继续读取
                readSize = ns.Read(bytes, 0, oneReadLen);
            }
            fs.Flush();
            fs.Close();
            fs = null;

            File.Move(tempFile, InstallFile);

            var    file = File.OpenRead(InstallFile);
            string md5  = Utility.GetMd5Hash(file);
            Debug.LogError("文件路径 :" + InstallFile + "  /文件名称/     :" + downUnit.fileName + "    /本地计算的md5值为/    :" + md5 + "            /服务器的md5/    :" + downUnit.md5 + "         /下载url  /      :" + downUnit.downUrl);

            file.Dispose();
            file.Close();

            if (md5 == downUnit.md5)
            {
                if (callback != null)
                {
                    callback(curSize, totalSize, true);
                }
            }
            else
            {
                if (errorCallback != null)
                {
                    errorCallback(downUnit);
                    Debug.LogError("MD5验证失败");
                }
                File.Delete(InstallFile);
                Debug.LogError("删除       删除      删除      删除      删除      删除      删除      删除      删除      删除      删除           " + InstallFile);
                //downloadThread.Stop();
            }
        }
        catch (WebException ex)
        {
            Debug.LogError(ex);
            if (errorCallback != null)
            {
                errorCallback(downUnit);
                Debug.Log("下载出错:" + ex.Message);
            }
        }
        finally
        {
            if (fs != null)
            {
                fs.Flush();
                fs.Close();
                fs = null;
            }
            if (ns != null)
            {
                ns.Close();
            }
            if (respone != null)
            {
                respone.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
        }
    }
Esempio n. 21
0
    /// <summary>
    /// 读取服务端版本号
    /// </summary>
    public void CheckCDNVersion()
    {
        downloadMgr.ClearAllDownloads();

        currentState = HotFix_ProjectState.CheckCDNVersion;

        string versionServerFile = GPath.PersistentAssetsPath + "versionServer.txt";

        if (File.Exists(versionServerFile))
        {
            File.Delete(versionServerFile);
        }

        var versionUnit = new DownloadUnit()
        {
            Name     = "version.txt",
            DownUrl  = GPath.CDNUrl + GPath.VersionFileName,
            SavePath = versionServerFile
        };

        versionUnit.ErrorFun = (DownloadUnit downUnit, string msg) =>
        {
            Debug.LogWarning("CheckAssetVersion Download Error " + msg + "\n" + downUnit.DownUrl);
            downloadMgr.DeleteDownload(versionUnit);
            UpdateError();
        };

        versionUnit.CompleteFun = (DownloadUnit downUnit) =>
        {
            if (!File.Exists(versionServerFile)) // 文件不存在,重新下载
            {
                UpdateError();
                return;
            }

            string versionStr = File.ReadAllText(versionServerFile);

            if (!int.TryParse(versionStr, out int curVersion))
            {
                Debug.LogError("CheckAssetVersion version Error " + versionStr);
                UpdateError();
                return;
            }

            serverVersion.Version = curVersion;

            Debug.Log("本地版本:" + clientVersion + " 服务器版本:" + curVersion);

            if (serverVersion.MidVer < clientVersion.MidVer)
            {
                UpdateError();
            }
            else if (serverVersion.MidVer > clientVersion.MidVer) // 换包
            {
                HotFixCallback(HotFix_ProjectState.RequestErrorRestart, "", (run) =>
                {
                });
            }
            else if (serverVersion.MinVer < clientVersion.MinVer)
            {
                Finished();
            }
            else
            {
                DownloadVersionFile();
            }
        };

        downloadMgr.DownloadAsync(versionUnit);
    }
Esempio n. 22
0
    public void OSSdownload(DownloadUnit downUnit, OSSFile of, Action <bool> callback)
    {
        //打开上次下载的文件
        long startPos = 0;
        //将文件的后缀名改为临时文件名 .temp
        string tempfilename = downUnit.fileName.Replace(Path.GetExtension(downUnit.fileName), ".temp");
        string tempFile     = downUnit.savePath + "/" + tempfilename;
        string InstallFile  = downUnit.savePath + "/" + downUnit.fileName;

        //若此文件已经存在 则直接返回文件的总大小
        if (File.Exists(InstallFile) && string.Equals(Utility.GetMd5Hash(File.OpenRead(InstallFile)), downUnit.md5))
        {
            //不执行下载流程
            //Debug.LogError("下载的文件 已经存在                 : " + InstallFile);
            if (callback != null)
            {
                callback(true);
            }
            return;
        }
        ///如果本地已经临时文件 获取临时文件的长度  断点续传
        if (System.IO.File.Exists(tempFile))
        {
            FileStream fs = File.OpenWrite(tempFile);
            startPos = fs.Length;
            fs.Seek(startPos, SeekOrigin.Current); //移动文件流中的当前指针
        }
        //必须要GMT时间
        string expire = DateTime.UtcNow.GetDateTimeFormats('r')[0].ToString();

        //Debug.Log(of.endpoint + "            " + of.objectName);
        //Debug.Log("OSS下载 url   @" + downUnit.downUrl + "@ 签名  @" + Utility.OSSSignature(of.endpoint, of.objectName, expire) + "@ 时间 @" + expire);

        HttpBase.OssGet(downUnit.downUrl, new KeyValuePair <string, string>[]
        {
            new KeyValuePair <string, string>("Date", expire),
            new KeyValuePair <string, string>("Authorization", Utility.OSSSignature(of.endpoint, of.objectName, expire)),
            new KeyValuePair <string, string>("Range", "bytes=" + (int)startPos + "-"),
        }, ((originalRequest, response) =>
        {
            //float fileSize = float.Parse(downUnit.size) / (1024 * 1024);
            //originalRequest.ConnectTimeout = new TimeSpan(600000);
            //originalRequest.Timeout = new TimeSpan(600000);
            FileStream fs = null;
            if (response == null)
            {
                // Debug.Log("请求为空" +downUnit.downUrl +" "+ downUnit.fileName);
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            if (!response.IsSuccess)
            {
                // Debug.Log("请求失败!" + response.StatusCode + " "+downUnit.downUrl+" "+ downUnit.fileName);
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            try
            {
                if (System.IO.File.Exists(tempFile))
                {
                    fs = File.OpenWrite(tempFile);
                }
                else
                {
                    string direName = Path.GetDirectoryName(tempFile);
                    if (!Directory.Exists(direName))
                    {
                        Directory.CreateDirectory(direName);
                    }

                    fs = new FileStream(tempFile, FileMode.Create);
                }

                var resp_bytes = response.Data;
                fs.Write(resp_bytes, 0, resp_bytes.Length);

                fs.Flush();
                fs.Close();
                fs = null;
                response.Dispose();

                if (!File.Exists(InstallFile))
                {
                    File.Move(tempFile, InstallFile);
                }

                var file = File.OpenRead(InstallFile);
                string md5 = Utility.GetMd5Hash(file);
                //Debug.LogError("文件路径 :" + InstallFile + "  /文件名称/     :" + downUnit.fileName +
                //               "    /本地计算的md5值为/    :" + md5 + "            /服务器的md5/    :" + downUnit.md5 +
                //               "         /下载url  /      :" + downUnit.downUrl);
                file.Dispose();
                file.Close();
                fs = null;
                if (md5 == downUnit.md5)
                {
                    //Debug.LogError("下载成功");
                    if (callback != null)
                    {
                        callback(true);
                    }

                    return;
                }
                else
                {
                    File.Delete(InstallFile);
                    //Debug.LogError(
                    //    "删除       删除      删除      删除      删除      删除      删除      删除      删除      删除      删除           " +
                    //    InstallFile);
                    if (callback != null)
                    {
                        callback(false);
                    }

                    return;
                }
            }
            catch (WebException ex)
            {
                Debug.Log("下载出错:");
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                response.Dispose();
            }
        }));
    }
 public DownloadProcessControl(BinInfo[] binfileInfos, IDownloadSender downloadSender)
 {
     TotalFileDownloadMissions = binfileInfos.Length;
     _downloadUnints           = new DownloadUnit[1];
     _downloadUnints[0]        = new DownloadUnit(binfileInfos, downloadSender);
 }
Esempio n. 24
0
 /// <summary>
 /// 单个下载
 /// </summary>
 /// <param name="downUnit"></param>
 /// <param name="callback"></param>
 /// <param name="errorCallback"></param>
 public static void SingleDownload(DownloadUnit downUnit, System.Action <long, long> callback, System.Action <DownloadUnit> errorCallback = null)
 {
 }
Esempio n. 25
0
 public DownloadFileMac(DownloadUnit unit)
 {
     DownUnit = unit;
 }