C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類_第1頁
C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類_第2頁
C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類_第3頁
C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類_第4頁
C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類_第5頁
已閱讀5頁,還剩19頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載客戶端工具類C#實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載的 Http Web 客戶端工具類 (C# DIY HttpWebClient),感興趣的朋友可以參考下本文,或許對你有所幫助代碼如下:/* .Net/C#: 實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載的 Http Web 客戶端工具類 (C# DIY HttpWebClient) * Reflector 了一下 System.Net.WebClient ,改寫或增加了若干: * DownLoad、Upload 相關(guān)方法! * DownLoad 相關(guān)改動較大! * 增加了 DataReceive、ExceptionOccurrs 事件!

2、* 了解服務(wù)器端與客戶端交互的 HTTP 協(xié)議參閱: * 使文件下載的自定義連接支持 FlashGet 的斷點續(xù)傳多線程鏈接下載! JSP/Servlet 實現(xiàn)! * * 使文件下載的自定義連接支持 FlashGet 的斷點續(xù)傳多線程鏈接下載! C#/ASP.Net 實現(xiàn)! * */ /2005-03-14 修訂: /* .Net/C#: 實現(xiàn)支持?jǐn)帱c續(xù)傳多線程下載的工具類 * Reflector 了一下 System.Net.WebClient ,改寫或增加了若干: * DownLoad、Upload 相關(guān)方法! * 增加了 DataReceive、ExceptionOccurrs事件 */

3、 namespace Microshaoft.Utils using System; using System.IO; using System.Net; using System.Text; using System.Security; using System.Threading; using System.Collections.Specialized; / / 記錄下載的字節(jié)位置 / public class DownLoadState private string _FileName; private string _AttachmentName; private int _Posi

4、tion; private string _RequestURL; private string _ResponseURL; 推薦精選private int _Length; private byte _Data; public string FileName get return _FileName; public int Position get return _Position; public int Length get return _Length; public string AttachmentName get return _AttachmentName; public str

5、ing RequestURL get return _RequestURL; public string ResponseURL get return _ResponseURL; 推薦精選public byte Data get return _Data; internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte Data) this._FileName = FileName; this.

6、_RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._AttachmentName = AttachmentName; this._Position = Position; this._Data = Data; this._Length = Length; internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, Threa

7、dCallbackHandler tch) this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = Position; this._Length = Length; this._ThreadCallback = tch; internal DownLoadState(string RequestURL, string ResponseURL, string F

8、ileName, string AttachmentName, int Position, int Length) this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = Position; this._Length = Length; private ThreadCallbackHandler _ThreadCallback; public HttpWebC

9、lient httpWebClient get 推薦精選return this._hwc; set this._hwc = value; internal Thread thread get return _thread; set _thread = value; private HttpWebClient _hwc; private Thread _thread; / internal void StartDownloadFileChunk() if (this._ThreadCallback != null) this._ThreadCallback(this._RequestURL, t

10、his._FileName, this._Position, this._Length); this._hwc.OnThreadProcess(this._thread); /委托代理線程的所執(zhí)行的方法簽名一致 public delegate void ThreadCallbackHandler(string S, string s, int I, int i); /異常處理動作 public enum ExceptionActions Throw, CancelAll, Ignore, Retry / / 包含 Exception 事件數(shù)據(jù)的類 / 推薦精選public class Exce

11、ptionEventArgs : System.EventArgs private System.Exception _Exception; private ExceptionActions _ExceptionAction; private DownLoadState _DownloadState; public DownLoadState DownloadState get return _DownloadState; public Exception Exception get return _Exception; public ExceptionActions ExceptionAct

12、ion get return _ExceptionAction; set _ExceptionAction = value; internal ExceptionEventArgs(System.Exception e, DownLoadState DownloadState) this._Exception = e; this._DownloadState = DownloadState; / / 包含 DownLoad 事件數(shù)據(jù)的類 / public class DownLoadEventArgs : System.EventArgs private DownLoadState _Down

13、loadState; public DownLoadState DownloadState 推薦精選get return _DownloadState; public DownLoadEventArgs(DownLoadState DownloadState) this._DownloadState = DownloadState; public class ThreadProcessEventArgs : System.EventArgs private Thread _thread; public Thread thread get return this._thread; public

14、ThreadProcessEventArgs(Thread thread) this._thread = thread; / / 支持?jǐn)帱c續(xù)傳多線程下載的類 / public class HttpWebClient private static object _SyncLockObject = new object(); public delegate void DataReceiveEventHandler(HttpWebClient Sender, DownLoadEventArgs e); public event DataReceiveEventHandler DataReceive;

15、 /接收字節(jié)數(shù)據(jù)事件 public delegate void ExceptionEventHandler(HttpWebClient Sender, ExceptionEventArgs e); public event ExceptionEventHandler ExceptionOccurrs; /發(fā)生異常事件 public delegate void ThreadProcessEventHandler(HttpWebClient Sender, ThreadProcessEventArgs e); public event ThreadProcessEventHandler Threa

16、dProcessEnd; /發(fā)生多線程處理完畢事件 private int _FileLength; /下載文件的總大小 public int FileLength get 推薦精選 return _FileLength; / / 分塊下載文件 / / URL 地址 / 保存到本地的路徑文件名 / 塊數(shù),線程數(shù) public void DownloadFile(string Address, string FileName, int ChunksCount) int p = 0; / position int s = 0; / chunk size string a = null; HttpW

17、ebRequest hwrq; HttpWebResponse hwrp = null; try hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address); hwrp = (HttpWebResponse) hwrq.GetResponse(); long L = hwrp.ContentLength; hwrq.Credentials = this.m_credentials; L = (L = -1) | (L 0x7fffffff) ? (long) 0x7fffffff) : L; /Int32.MaxValue 該常

18、數(shù)的值為 2,147,483,647; 即十六進(jìn)制的 0x7FFFFFFF int l = (int) L; this._FileLength = l; / 在本地預(yù)定空間(竟然在多線程下不用先預(yù)定空間) / FileStream sw = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); / sw.Write(new bytel, 0, l); / sw.Close(); / sw = null; bool b = (hwrp.HeadersAccept-Ra

19、nges != null & hwrp.HeadersAccept-Ranges = bytes); a = hwrp.HeadersContent-Disposition; /attachment if (a != null) a = a.Substring(a.LastIndexOf(filename=) + 9); else a = FileName; 推薦精選int ss = s; if (b) s = l / ChunksCount; if (s s) l -= s; if (l 0) DownLoadState x = new DownLoadState(Address, hwrp

20、.ResponseUri.AbsolutePath, FileName, a, p, s, new ThreadCallbackHandler(this.DownloadFileChunk); / 單線程下載 / x.StartDownloadFileChunk(); x.httpWebClient = this; /多線程下載 Thread t = new Thread(new ThreadStart(x.StartDownloadFileChunk); /this.OnThreadProcess(t); t.Start(); p += s; s = ss; byte buffer = th

21、is.ResponseAsBytes(Address, hwrp, s, FileName); this.OnThreadProcess(Thread.CurrentThread); / lock (_SyncLockObject) / / this._Bytes += buffer.Length; / catch (Exception e) ExceptionActions ea = ExceptionActions.Throw; if (this.ExceptionOccurrs != null) 推薦精選 DownLoadState x = new DownLoadState(Addre

22、ss, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; if (ea = ExceptionActions.Throw) if (!(e is WebException) & !(e is SecurityException) throw new WebException(net_webclient, e); throw;

23、internal void OnThreadProcess(Thread t) if (ThreadProcessEnd != null) ThreadProcessEventArgs tpea = new ThreadProcessEventArgs(t); ThreadProcessEnd(this, tpea); / / 下載一個文件塊,利用該方法可自行實現(xiàn)多線程斷點續(xù)傳 / / URL 地址 / 保存到本地的路徑文件名 / 塊大小 public void DownloadFileChunk(string Address, string FileName, int FromPositio

24、n, int Length) HttpWebResponse hwrp = null; string a = null; try /this._FileName = FileName; HttpWebRequest hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address); /hwrq.Credentials = this.m_credentials; hwrq.AddRange(FPosition); hwrp = (HttpWebResponse) hwrq.GetResponse(); a = hwrp.HeadersC

25、ontent-Disposition; /attachment 推薦精選if (a != null) a = a.Substring(a.LastIndexOf(filename=) + 9); else a = FileName; byte buffer = this.ResponseAsBytes(Address, hwrp, Length, FileName); / lock (_SyncLockObject) / / this._Bytes += buffer.Length; / catch (Exception e) ExceptionActions ea = ExceptionAc

26、tions.Throw; if (this.ExceptionOccurrs != null) DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, FromPosition, Length); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; if (ea = ExceptionActions.Thro

27、w) if (!(e is WebException) & !(e is SecurityException) throw new WebException(net_webclient, e); throw; internal byte ResponseAsBytes(string RequestURL, WebResponse Response, long Length, string FileName) string a = null; /AttachmentName int P = 0; /整個文件的位置指針 int num2 = 0; try a = Response.HeadersC

28、ontent-Disposition; /attachment 推薦精選if (a != null) a = a.Substring(a.LastIndexOf(filename=) + 9); long num1 = Length; /Response.ContentLength; bool flag1 = false; if (num1 = -1) flag1 = true; num1 = 0x10000; /64k byte buffer1 = new byte(int) num1; int p = 0; /本塊的位置指針 string s = Response.HeadersConte

29、nt-Range; if (s != null) s = s.Replace(bytes , ); s = s.Substring(0, s.IndexOf(-); P = Convert.ToInt32(s); int num3 = 0; Stream S = Response.GetResponseStream(); do num2 = S.Read(buffer1, num3, (int) num1) - num3); num3 += num2; if (flag1 & (num3 = num1) num1 += 0x10000; byte buffer2 = new byte(int)

30、 num1; Buffer.BlockCopy(buffer1, 0, buffer2, 0, num3); buffer1 = buffer2; / lock (_SyncLockObject) / / this._bytes += num2; / if (num2 0) if (this.DataReceive != null) byte buffer = new bytenum2; Buffer.BlockCopy(buffer1, p, buffer, 0, buffer.Length); DownLoadState dls = new DownLoadState(RequestURL

31、, Response.ResponseUri.AbsolutePath, FileName, a, P, num2, buffer); 推薦精選DownLoadEventArgs dlea = new DownLoadEventArgs(dls); /觸發(fā)事件 this.OnDataReceive(dlea); /System.Threading.Thread.Sleep(100); p += num2; /本塊的位置指針 P += num2; /整個文件的位置指針 else break; while (num2 != 0); S.Close(); S = null; if (flag1) b

32、yte buffer3 = new bytenum3; Buffer.BlockCopy(buffer1, 0, buffer3, 0, num3); buffer1 = buffer3; return buffer1; catch (Exception e) ExceptionActions ea = ExceptionActions.Throw; if (this.ExceptionOccurrs != null) DownLoadState x = new DownLoadState(RequestURL, Response.ResponseUri.AbsolutePath, FileN

33、ame, a, P, num2); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; if (ea = ExceptionActions.Throw) if (!(e is WebException) & !(e is SecurityException) throw new WebException(net_webclient, e); throw; 推薦精選return null; private void OnDataR

34、eceive(DownLoadEventArgs e) /觸發(fā)數(shù)據(jù)到達(dá)事件 DataReceive(this, e); public byte UploadFile(string address, string fileName) return this.UploadFile(address, POST, fileName, file); public string UploadFileEx(string address, string method, string fileName, string fieldName) return Encoding.ASCII.GetString(Uplo

35、adFile(address, method, fileName, fieldName); public byte UploadFile(string address, string method, string fileName, string fieldName) byte buffer4; FileStream stream1 = null; try fileName = Path.GetFullPath(fileName); string text1 = - + DateTime.Now.Ticks.ToString(x); string text2 = application/oct

36、et-stream; stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read); WebRequest request1 = WebRequest.Create(this.GetUri(address); request1.Credentials = this.m_credentials; request1.ContentType = multipart/form-data; boundary= + text1; request1.Method = method; string textArray1 = new str

37、ing7 -, text1, rnContent-Disposition: form-data; name= + fieldName + ; filename=, Path.GetFileName(fileName), rnContent-Type: , text2, rnrn; string text3 = string.Concat(textArray1); byte buffer1 = Encoding.UTF8.GetBytes(text3); byte buffer2 = Encoding.ASCII.GetBytes(rn- + text1 + rn); long num1 = 0

38、x7fffffffffffffff; try num1 = stream1.Length; request1.ContentLength = (num1 + buffer1.Length) + buffer2.Length; 推薦精選 catch byte buffer3 = new byteMath.Min(0x2000, (int) num1); using (Stream stream2 = request1.GetRequestStream() int num2; stream2.Write(buffer1, 0, buffer1.Length); do num2 = stream1.

39、Read(buffer3, 0, buffer3.Length); if (num2 != 0) stream2.Write(buffer3, 0, num2); while (num2 != 0); stream2.Write(buffer2, 0, buffer2.Length); stream1.Close(); stream1 = null; WebResponse response1 = request1.GetResponse(); buffer4 = this.ResponseAsBytes(response1); catch (Exception exception1) if

40、(stream1 != null) stream1.Close(); stream1 = null; if (!(exception1 is WebException) & !(exception1 is SecurityException) /throw new WebException(SR.GetString(net_webclient), exception1); throw new WebException(net_webclient, exception1); throw; return buffer4; private byte ResponseAsBytes(WebRespon

41、se response) int num2; 推薦精選long num1 = response.ContentLength; bool flag1 = false; if (num1 = -1) flag1 = true; num1 = 0x10000; byte buffer1 = new byte(int) num1; Stream stream1 = response.GetResponseStream(); int num3 = 0; do num2 = stream1.Read(buffer1, num3, (int) num1) - num3); num3 += num2; if

42、(flag1 & (num3 = num1) num1 += 0x10000; byte buffer2 = new byte(int) num1; Buffer.BlockCopy(buffer1, 0, buffer2, 0, num3); buffer1 = buffer2; while (num2 != 0); stream1.Close(); if (flag1) byte buffer3 = new bytenum3; Buffer.BlockCopy(buffer1, 0, buffer3, 0, num3); buffer1 = buffer3; return buffer1;

43、 private NameValueCollection m_requestParameters; private Uri m_baseAddress; private ICredentials m_credentials = CredentialCache.DefaultCredentials; public ICredentials Credentials get return this.m_credentials; set this.m_credentials = value; 推薦精選 public NameValueCollection QueryString get if (thi

44、s.m_requestParameters = null) this.m_requestParameters = new NameValueCollection(); return this.m_requestParameters; set this.m_requestParameters = value; public string BaseAddress get if (this.m_baseAddress != null) return this.m_baseAddress.ToString(); return string.Empty; set if (value = null) |

45、(value.Length = 0) this.m_baseAddress = null; else try this.m_baseAddress = new Uri(value); catch (Exception exception1) throw new ArgumentException(value, exception1); 推薦精選 private Uri GetUri(string path) Uri uri1; try if (this.m_baseAddress != null) uri1 = new Uri(this.m_baseAddress, path); else u

46、ri1 = new Uri(path); if (this.m_requestParameters = null) return uri1; StringBuilder builder1 = new StringBuilder(); string text1 = string.Empty; for (int num1 = 0; num1 this.m_requestParameters.Count; num1+) builder1.Append(text1 + this.m_requestParameters.AllKeysnum1 + = + this.m_requestParameters

47、num1); text1 = &; UriBuilder builder2 = new UriBuilder(uri1); builder2.Query = builder1.ToString(); uri1 = builder2.Uri; catch (UriFormatException) uri1 = new Uri(Path.GetFullPath(path); return uri1; / / 測試類 / class AppTest 推薦精選int _k = 0; int _K = 0; static void Main() AppTest a = new AppTest(); Mi

48、croshaoft.Utils.HttpWebClient x = new Microshaoft.Utils.HttpWebClient(); a._K = 10; /訂閱 DataReceive事件 x.DataReceive += new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler(a.x_DataReceive); /訂閱 ExceptionOccurrs事件 x.ExceptionOccurrs += new Microshaoft.Utils.HttpWebClient.ExceptionEventHandler(

49、a.x_ExceptionOccurrs); x.ThreadProcessEnd += new Microshaoft.Utils.HttpWebClient.ThreadProcessEventHandler(a.x_ThreadProcessEnd); string F = http:/localhost/download/phpMyAdmin-2.6.1-pl2.zip; F = a._F = F; string f = F.Substring(F.LastIndexOf(/) + 1); /(new System.Threading.Thread(new System.Threadi

50、ng.ThreadStart(new ThreadProcessState(F, E:temp + f, 10, x).SThreadProcess).Start(); x.DownloadFile(F, d:temp + f, a._K); / x.DownloadFileChunk(F, E:temp + f,15,34556); System.Console.ReadLine(); / string uploadfile = e:test_local.rar; / string str = x.UploadFileEx(http:/localhost/phpmyadmin/uploadaction.php, POST,

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論