少年修仙传客户端代码仓库
client_linchunjie
2019-04-17 f1f2599ba0e6b64358ffef7ae5c9f9af3ed8b8b4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//#define UseWebClient
 
using UnityEngine;
using System.Collections;
using System.Net;
using System.IO;
using System.ComponentModel;
using System;
using System.Threading;
 
public class RemoteFile
{
    static bool m_ProcessErroring = false;
    public static bool processErroring
    {
        get { return m_ProcessErroring; }
    }
 
    public static int maxDownLoadTask = 48;
    public static int MaxConnectLimit = 48;
    static int gDownloadIsRunningCount;
    public static int DownloadIsRunningCount
    {
        get { return gDownloadIsRunningCount; }
    }
 
    public static int gStartTickcount = 0;
    static long gTotalDownloadSize = 0L;  //已下载的字节数
    static object lockObj = new object();
    public static long TotalDownloadedSize
    {
        get
        {
            return System.Threading.Interlocked.Read(ref gTotalDownloadSize);
        }
        set
        {
            gTotalDownloadSize = value;
        }
    }
 
    static float downloadSpeedRef = 0f; //字节/秒
    static long downloadSizeRef = 0L;
 
    public static string DownloadSpeed
    {
        get
        {
            float speed = downloadSpeedRef;
            if (RemoteFile.gStartTickcount != 0)
            {
                float second = Mathf.Abs(System.Environment.TickCount - RemoteFile.gStartTickcount) / 1000f;
                if (second > 1f || (downloadSpeedRef <= 0.1f && TotalDownloadedSize > 0))
                {
                    if (second > 0f)
                    {
                        var delta = TotalDownloadedSize - downloadSizeRef;
                        downloadSizeRef = TotalDownloadedSize;
 
                        speed = (delta / second + downloadSpeedRef) * 0.5f;
                        downloadSpeedRef = speed;
                        RemoteFile.gStartTickcount = System.Environment.TickCount;
                    }
                }
            }
 
            if (speed > 1048576f)
            {
                return StringUtility.Contact((speed / 1048576f).ToString("f1"), " M/S");
            }
            else if (speed > 1024f)
            {
                return StringUtility.Contact((speed / 1024f).ToString("f1"), " KB/S");
            }
            else
            {
                return StringUtility.Contact(speed.ToString("f1"), " B/S");
            }
        }
    }
 
    public AssetVersion assetVersion { get; private set; }
    protected string mRemoteFile;
    protected string localFile;
    bool speedLimit = false;
 
    protected string mLocalFileTemp; //临时文件
 
    protected System.DateTime mRemoteLastModified;
    protected System.DateTime mLocalLastModified;
    protected long mRemoteFileSize = 0;
    public static long TotalRemoteFileSize = 0L;
 
    const int bufferSize = 8192;
    byte[] buff;
 
    HttpWebRequest headRequest;
    HttpWebResponse headResponse;
    HttpWebRequest fileRequest = null;
    HttpWebResponse fileResponse = null;
 
    Action<bool, AssetVersion> onCompleted;
 
    protected bool mHadError = false;
    public bool HaveError
    {
        get { return mHadError; }
    }
 
    bool m_Done = false;
    public bool done
    {
        get { return m_Done; }
        private set
        {
            m_Done = value;
            if (value)
            {
                state = State.Stoped;
                if (onCompleted != null)
                {
                    onCompleted(!HaveError, assetVersion);
                    onCompleted = null;
                }
            }
        }
    }
 
    State state = State.Wait;
 
    int read_Stream_startTickcount = 0; //请求操作开始,用于超时判断
    int timeOut = 5000; //超时时间
 
    public static void Prepare()
    {
        gDownloadIsRunningCount = 0;
        gStartTickcount = System.Environment.TickCount;
        TotalDownloadedSize = 0L;
        downloadSpeedRef = 0f;
        downloadSizeRef = 0L;
    }
 
    public void Init(string remoteFile, string _localFile, AssetVersion _assetVersion, bool _speedLimit = false)
    {
        mRemoteFile = remoteFile;
        localFile = _localFile;
        assetVersion = _assetVersion;
        this.speedLimit = _speedLimit;
    }
 
    public void Begin(Action<bool, AssetVersion> _onCompleted)
    {
        onCompleted = _onCompleted;
        SnxxzGame.Instance.StartCoroutine(Co_DownloadRemoteFile());
    }
 
    bool stop = false;
 
    public void Stop()
    {
        if (stop)
        {
            return;
        }
 
        stop = true;
        try
        {
            if (headRequest != null)
            {
                headRequest.Abort();
                headRequest = null;
            }
 
            if (headResponse != null)
            {
                headResponse.Close();
                headResponse = null;
            }
 
            if (fileRequest != null)
            {
                fileRequest.Abort();
                fileRequest = null;
            }
 
            if (fileResponse != null)
            {
                fileResponse.Close();
                fileResponse = null;
            }
 
            if (fs != null)
            {
                fs.Flush();
                fs.Close();
                fs = null;
            }
 
            if (inStream != null)
            {
                inStream.Close();
                inStream = null;
            }
        }
        catch (Exception ex)
        {
            Debug.Log(ex);
        }
        finally
        {
            onCompleted = null;
            mHadError = false;
            if (state == State.Working)
            {
                gDownloadIsRunningCount--;
            }
        }
    }
 
    private void OnDispose()
    {
 
    }
 
    void MakeSureDirectory(string filePath)
    {
        string dir = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
    }
 
    bool Move(string sourceFile, string destFile)
    {
        bool ret = true;
#if !UNITY_WEBPLAYER
        try
        {
            if (speedLimit)
            {
                ThreadPool.QueueUserWorkItem((object _obj) =>
                {
                    File.Move(sourceFile, destFile);
                });
            }
            else
            {
                File.Move(sourceFile, destFile);
            }
        }
        catch (Exception ex)
        {
            DebugEx.LogError(ex.Message);
            ret = false;
        }
#endif
        return ret;
    }
 
    IEnumerator Co_DownloadRemoteFile()
    {
        done = false;
 
        while (gDownloadIsRunningCount >= maxDownLoadTask)
        {
            if (stop)
            {
                yield break;
            }
            //超过最大任务数时,先等待
            yield return null;
        }
 
        while (assetVersion != null && assetVersion.extersion == ".manifest" && !AssetVersionUtility.GetAssetVersion(assetVersion.relativePath.Replace(".manifest", "")).localValid)
        {
            if (stop)
            {
                yield break;
            }
            yield return null;
        }
 
        state = State.Working;
 
        gDownloadIsRunningCount++;
        mHadError = false;
        fileWriteState = FileWriteState.None;
        mLocalFileTemp = localFile + ".tmp";  //先下载为临时文件
 
        MakeSureDirectory(mLocalFileTemp);   //确保文件写入目录存在
        mLocalLastModified = DateTime.MinValue;
        long localFileSize = 0L;
#if !UNITY_WEBPLAYER
        mLocalLastModified = File.GetLastWriteTime(mLocalFileTemp);
#endif
        headRequest = (HttpWebRequest)System.Net.WebRequest.Create(mRemoteFile);
        if (headRequest.ServicePoint.ConnectionLimit < RemoteFile.MaxConnectLimit)
        {
            headRequest.ServicePoint.ConnectionLimit = RemoteFile.MaxConnectLimit;
        }
        headRequest.Method = "HEAD"; // Only the header info, not full file!
        headRequest.ServicePoint.Expect100Continue = false;
        headRequest.Timeout = 3000;
        headRequest.Proxy = null;
        headRequest.KeepAlive = false;
        bool isAcceptRange = true;
        bool headRequestOk = false; //是否支持断点续传
 
        int tick1 = 0;
        try
        {
            headRequest.BeginGetResponse( //改为异步的方法
                (x) =>
                {
                    try
                    {
                        headResponse = (x.AsyncState as HttpWebRequest).EndGetResponse(x) as HttpWebResponse;
                        mRemoteLastModified = headResponse.LastModified;
                        mRemoteFileSize = headResponse.ContentLength;
                        if (headResponse.Headers["Accept-Ranges"] != null)
                        {
                            string s = headResponse.Headers["Accept-Ranges"];
                            if (s == "none")
                            {
                                isAcceptRange = false;
                            }
                        }
                        System.Threading.Interlocked.Add(ref RemoteFile.TotalRemoteFileSize, mRemoteFileSize);
                        headRequestOk = true;
                    }
                    catch (Exception ex)
                    {
                        DebugEx.LogWarning("ERROR: " + ex);
                        mHadError = true;
                    }
                    finally
                    {
                        if (headResponse != null)
                        {
                            headResponse.Close();
                            headResponse = null;
                        }
                        if (headRequest != null)
                        {
                            headRequest.Abort();
                            headRequest = null;
                        }
                    }
 
                }, headRequest);
            tick1 = System.Environment.TickCount;
        }
        catch (WebException webEx)
        {
            DebugEx.LogWarning("<color=red>Request File Head ERROR: " + mRemoteFile + "</color>");
            DebugEx.LogWarning("ERROR: " + webEx);
            mHadError = true;
            gDownloadIsRunningCount--;
            done = true;
            yield break;
        }
        catch (System.Exception e)
        {
            DebugEx.LogWarning("<color=red>Request File Head ERROR: " + mRemoteFile + "</color>");
            DebugEx.LogWarning("ERROR: " + e);
            mHadError = true;
            gDownloadIsRunningCount--;
            done = true;
            yield break;
        }
 
        while (!headRequestOk && !mHadError)
        {
            if (stop)
            {
                yield break;
            }
 
            if (processErroring)
            {
                mHadError = true;
                break;
            }
            float dur = System.Environment.TickCount - tick1;
            if (dur > timeOut)
            {
                DebugEx.LogWarningFormat("获取远程文件{0} 信息超时!", mRemoteFile);
                mHadError = true;
                break;
            }
            yield return null;
        }
        if (mHadError)
        {
            DebugEx.LogWarningFormat("获取远程文件{0} 信息失败!", mRemoteFile);
            if (headRequest != null)
            {
                headRequest.Abort();
                headRequest = null;
            }
 
            done = true;
            gDownloadIsRunningCount--;
            yield break;
        }
 
        //判断是否有已经下载部分的临时文件
        if (File.Exists(mLocalFileTemp))
        { // This will not work in web player!
            //判断是否断点续传, 依据临时文件是否存在,以及修改时间是否小于服务器文件时间
#if !UNITY_WEBPLAYER
            localFileSize = (File.Exists(mLocalFileTemp)) ? (new FileInfo(mLocalFileTemp)).Length : 0L;
#endif
            bool outDated = IsOutdated;
            if (localFileSize == mRemoteFileSize && !outDated)
            {
                gDownloadIsRunningCount--;
                mHadError = !Move(mLocalFileTemp, localFile);//把临时文件改名为正式文件
                done = true;
                yield break; // We already have the file, early out
            }
            else if (localFileSize > mRemoteFileSize || outDated)
            {
                if (!outDated) DebugEx.LogWarning("Local file is larger than remote file, but not outdated. PANIC!");
                if (outDated)
                {
                    DebugEx.LogWarning(mLocalFileTemp + " Local file is outdated, deleting");
                }
                try
                {
                    if (File.Exists(mLocalFileTemp))
                        File.Delete(mLocalFileTemp);
                }
                catch (System.Exception e)
                {
                    DebugEx.LogWarning("<color=red>Could not delete local file</color>");
                    DebugEx.LogError(e);
                }
 
                while (File.Exists(mLocalFileTemp))
                {
                    if (stop)
                    {
                        yield break;
                    }
                    yield return null;
                }
 
                localFileSize = 0;
            }
        }
 
        if (mHadError)
        {
            gDownloadIsRunningCount--;
            done = true;
            yield break;
        }
 
        if (File.Exists(localFile))
        {
            try
            {
                if (File.Exists(localFile))
                    File.Delete(localFile);
            }
            catch (System.Exception e)
            {
                DebugEx.LogWarning("<color=red>Could not delete local file</color>");
                DebugEx.LogWarning(e);
            }
            while (File.Exists(localFile))
            {
                if (stop)
                {
                    yield break;
                }
                yield return null;
            }
        }
 
#if UseWebClient //|| UNITY_IOS
        using (WebClient client = new WebClient()) {
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
            client.DownloadFileAsync(new Uri(mRemoteFile), mLocalFileTemp);
        }
        
        while (!done) {
            yield return null;
        }
        mHadError = !Move(mLocalFileTemp, localFile);//把临时文件改名为正式文件
#else
        try
        {
            fileRequest = (HttpWebRequest)HttpWebRequest.Create(mRemoteFile);
            if (fileRequest.ServicePoint.ConnectionLimit < RemoteFile.MaxConnectLimit)
            {
                fileRequest.ServicePoint.ConnectionLimit = RemoteFile.MaxConnectLimit;
            }
            fileRequest.ServicePoint.Expect100Continue = false;
            fileRequest.Timeout = 3000;
            fileRequest.Proxy = null;
            fileRequest.KeepAlive = false;
 
            if (localFileSize != 0L && isAcceptRange)
            {
                fileRequest.AddRange((int)localFileSize, (int)mRemoteFileSize - 1);
            }
#if !UNITY_WEBPLAYER
            fileRequest.Method = WebRequestMethods.Http.Get;
#endif
            fileRequest.BeginGetResponse(AsynchCallback, fileRequest);
            tick1 = System.Environment.TickCount;
        }
        catch (System.Exception ex)
        {
            DebugEx.LogWarning("BeginGetResponse exception: " + ex.Message);
            DebugEx.LogWarning(ex);
            if (fileRequest != null)
            {
                fileRequest.Abort();
                fileRequest = null;
            }
            mHadError = true;
            done = true;
            gDownloadIsRunningCount--;
            yield break;
        }
 
        while (fileResponse == null && !mHadError)
        { // Wait for asynch to finish
 
            if (stop)
            {
                yield break;
            }
 
            if (processErroring)
            {
                mHadError = true;
                break;
            }
            float dur = System.Environment.TickCount - tick1;
            if (dur > timeOut)
            {
                DebugEx.LogWarningFormat("下载远程文件{0} 超时!", mRemoteFile);
                mHadError = true;
                break;
            }
            yield return null;
        }
 
        if (mHadError)
        {
            DebugEx.LogWarningFormat("[RemoteFile] 远程文件{0} 下载失败! ", localFile);
            if (fileRequest != null)
            {
                fileRequest.Abort();
                fileRequest = null;
            }
            if (fileResponse != null)
            {
                fileResponse.Close();
                fileResponse = null;
            }
            done = true;
            gDownloadIsRunningCount--;
            yield break;
        }
 
        try
        {
            inStream = fileResponse.GetResponseStream();
            fs = new FileStream(mLocalFileTemp, (localFileSize > 0) ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            if (buff == null)
            {
                buff = new byte[bufferSize];
            }
            fileWriteState = FileWriteState.Writting;
            inStream.BeginRead(buff, 0, bufferSize, ReadDataCallback, null);
            read_Stream_startTickcount = System.Environment.TickCount;
        }
        catch (Exception ex)
        {
            DebugEx.LogWarning("<color=red>ERROR: " + mRemoteFile + "</color>");
            DebugEx.LogWarning(ex);
            if (inStream != null)
            {
                inStream.Close();
                inStream = null;
            }
            if (fs != null)
            {
                fs.Close();
                fs = null;
            }
            if (fileResponse != null)
            {
                fileResponse.Close();
                fileResponse = null;
            }
            mHadError = true;
            fileWriteState = FileWriteState.Error;
        }
 
        while (fileWriteState == FileWriteState.Writting)
        {
            if (stop)
            {
                yield break;
            }
 
            if (processErroring)
            {
                fileWriteState = FileWriteState.Error;
                break;
            }
            if (downloadSpeedRef == 0)
            {
                int dura = System.Environment.TickCount - read_Stream_startTickcount;
                if (dura > timeOut)
                {
                    fileWriteState = FileWriteState.Timeout;
                    DebugEx.LogWarningFormat("[RemoteFile] 远程文件{0} 读取超时{1}!", mRemoteFile, dura);
                    break;
                }
            }
 
            yield return null;
        }
 
        if (fileRequest != null)
        {
            fileRequest.Abort();
            fileRequest = null;
        }
        if (fileWriteState == FileWriteState.Error || fileWriteState == FileWriteState.Timeout)
        {
            DebugEx.LogWarningFormat("[RemoteFile] 远程文件{0} 下载失败! ", localFile);
            if (fileResponse != null)
            {
                fileResponse.Close();
                fileResponse = null;
            }
 
            gDownloadIsRunningCount--;
            mHadError = true;
            done = true;
            yield break;
        }
 
        try
        {
            FileInfo localTempFileInfo = new FileInfo(mLocalFileTemp);
            if (localTempFileInfo.Exists)
            { //临时文件存在,需要判断大小是否一致
              //判断临时文件和远程文件size是否一致
                if (localTempFileInfo.Length != mRemoteFileSize && mRemoteFileSize != 0L)
                {
                    mHadError = true;
                    DebugEx.LogError(string.Format(localFile + " 下载完成后, 但是大小{0} 和远程文件不一致 {1}", localTempFileInfo.Length, mRemoteFileSize));
                }
                else
                {  //大小一致 
                    mHadError = !Move(mLocalFileTemp, localFile);//把临时文件改名为正式文件
                }
            }
            else
            { //临时文件不存在
                mHadError = true;
            }
#endif
        }
        catch (Exception ex)
        {
            DebugEx.LogError(ex);
            mHadError = true;
        }
 
        yield return null;
        gDownloadIsRunningCount--;
        done = true;
    }
 
    bool IsOutdated
    {
        get
        {
            if (File.Exists(mLocalFileTemp))
                return mRemoteLastModified > mLocalLastModified;
            return false;
        }
    }
 
    enum FileWriteState
    {
        None,
        Writting,
        Completed,
        Error,
        Timeout,
    }
 
    Stream inStream;
    FileStream fs;
    FileWriteState fileWriteState = FileWriteState.None;  //下载文件写入状态
 
    void ReadDataCallback(IAsyncResult ar)
    {
        if (stop)
        {
            return;
        }
 
        try
        {
            if (inStream != null)
            {
                int read = inStream.EndRead(ar);
                lock (lockObj)
                {
                    gTotalDownloadSize += read;
                }
 
                if (read > 0)
                {
                    fs.BeginWrite(buff, 0, read, WriteDataCallBack, fs);
                }
                else
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
 
                    if (inStream != null)
                    {
                        inStream.Close();
                        inStream = null;
                    }
 
                    if (fileResponse != null)
                    {
                        fileResponse.Close();
                        fileResponse = null;
                    }
 
                    fileWriteState = FileWriteState.Completed;
                }
            }
        }
        catch (Exception ex)
        {
            if (!processErroring)
            {
                DebugEx.LogWarning(ex);
                DebugEx.LogWarning("ReadDataCallback 异常信息: " + ex.Message);
            }
            if (fs != null)
            {
                fs.Close();
                fs = null;
            }
            if (inStream != null)
            {
                inStream.Close();
                inStream = null;
            }
            fileWriteState = FileWriteState.Error;
        }
    }
 
    void WriteDataCallBack(IAsyncResult _asyncResult)
    {
        fs.Flush();
        inStream.BeginRead(buff, 0, bufferSize, new AsyncCallback(ReadDataCallback), null);
        read_Stream_startTickcount = System.Environment.TickCount;
    }
 
#if UseWebClient //|| UNITY_IOS
    protected void DownloadCompleted(System.Object sender, AsyncCompletedEventArgs e) {
        done = true;
    }
#else
    // Throwind an exception here will not propogate to unity!
    protected void AsynchCallback(IAsyncResult result)
    {
        try
        {
            if (result == null)
            {
                DebugEx.LogError("Asynch result is null!");
                mHadError = true;
            }
 
            HttpWebRequest webRequest = (HttpWebRequest)result.AsyncState;
            if (webRequest == null)
            {
                DebugEx.LogError("Could not cast to web request");
                mHadError = true;
            }
 
            fileResponse = webRequest.EndGetResponse(result) as HttpWebResponse;
            if (fileResponse == null)
            {
                DebugEx.LogError("Asynch response is null!");
                mHadError = true;
            }
        }
        catch (Exception ex)
        {
            mHadError = true;
            DebugEx.LogWarning(ex);
            DebugEx.LogWarning("[RemoteFile] AsynchCallback 异常: " + ex.Message);
        }
    }
#endif
 
    public enum State
    {
        Wait,
        Working,
        Stoped,
    }
}