C # Programming Summary (12) breakpoint Continuation

Source: Internet
Author: User

C # Programming Summary (12) breakpoint Continuation

We often use download tools such as bit Elves, Thunderbolt, FlashGet, which support the continuation of breakpoints.

The continuation of a breakpoint can continue after the download task is paused, without having to re-download the server's starting location to be notified when downloading. If you allow multi-threaded multipart downloads, you must provide a start-to-cut location. After all, you can choose to download a fragment, the entire file stream of bytes, you can intercept the flow of fragments, can also realize the accumulation of streams, the final file download.

First, the principle

A new header attribute in http/1.1: Range, is also now many known as multi-threaded download tools (such as FlashGet, thunder, etc.) to achieve the core of multi-threaded download. Older versions of the HTTP protocol are not supported, so some older servers do not support the continuation of breakpoints.

Range (Request parameter)

For the request header, specify the position of the first byte and the position of the last byte, in general format:

Range: (Unit=first byte pos)-[last byte POS]

For example: range:100-199, fetch bytes from 100 to 199 of the file stream.

range:100, taking all bytes after the position is 100. If range is positive, the server should start sending data from the specified range parameter to the end of the data in the HTTP entity.

Range:-99, which takes the starting 100 bytes. If range is negative, the server should start sending data from the beginning of the data in the HTTP entity to the specified range parameter.

Content-range (response parameter)

For the response header, which specifies the insertion position of a part of the entire entity, he also indicates the length of the entire entity. When the server returns a partial response to the customer, it must describe the extent of the response coverage and the entire length of the entity.

General format:

Example: Content-range:bytes 1024000-1126399/7421120

HTTP protocol: http://www.w3.org/Protocols/rfc2616/rfc2616.html

Second, the implementation of C #

Adding a specified range of byte range headers to a request in C # using the AddRange method

System.Net.HttpWebRequest

All the methods:

Examples of commonly used methods are:

void AddRange (long from, long to);
Specifies the starting and ending position of the range to request data for the fragment.
        Summary:     adds a specified range of byte range headers to the request. ////        Parameters:        //   from:        //     where to start sending data. ////   to:        //     stop sending data to the location. Public        void AddRange (long from, long to);

We use this method, based on the HTTP protocol to achieve the continuation of the breakpoint, support pause, continue the download function, in order to more clearly display the effect, provides a progress bar display. :

Request

The range parameter of the request, we can clearly see the specific value, this is the requested fragment. Here you can see clearly the HTTP protocol version, request method, request address and other information

Response

The server returns only the data for that fragment, based on the requested range parameter. We can clearly see the exact value of the Content-range.

Note: The returned statuscode becomes partialcontent, and the description is part of the data.

Code meaning
Request for a successful return
206 Partial Content Part data

Download the core code:

        <summary>//download///</summary> public void Download () {//            Counting from 0, you need to subtract a long from = this.currentsize;            if (from < 0) {from = 0;            } Long to = This.currentsize + this.step-1;            if (to >= this.totalsize && this.totalsize > 0) {to = this.totalsize-1; } this.        Download (from, to);        }///<summary>//download//</summary>//<param name= "url" ></param> <param name= "range" ></param> public void Download (long from,long to) {if (            This.totalsize = = 0) {gettotalsize (); } if (from >= this.totalsize | | this.currentsize >= this.totalsize) {THIS.ISFI                Nished = true;            Return } httpwebRequest Request = (HttpWebRequest) httpwebrequest.create (URL); Request.                        Method = "GET"; Request.            AddRange ("bytes", from, to); HttpWebResponse response = (HttpWebResponse) request.            GetResponse (); string result = String.            Empty; if (response! = NULL) {byte[] buffer = this.                Buffer; using (Stream stream = response.                    GetResponseStream ()) {int readtotalsize = 0; int size = stream. Read (buffer, 0, buffer.                    Length); while (Size > 0) {//writes only the read-out bytes to file FS.                        Write (buffer, 0, size);                        Readtotalsize + = size; size = stream. Read (buffer, 0, buffer.                    Length);                    }//Update current progress this.currentsize + = Readtotalsize; If the Content-range value in the returned response header is NULL, the server does not support the Range property,Continuation of the breakpoint, returning all data if (response.                    headers["Content-range"] = = null) {this.isfinished = true; }                }            }        }

Project Source:

Http://files.cnblogs.com/yank/DownloadSample.rar

Three, multi-threaded download

The above example provides a simple breakpoint continuation function, if you want to further implement multi-threaded download. The principle is very simple, we only need to download according to the size of the file, do not block the start of a thread to download, the thread is only responsible for downloading their own fragments, be sure to set the value of range strictly. The concrete realization here no longer introduces, if interested, down can continue to study.

A reminder: How does a multi-threaded download of a byte stream be saved as a file and must be in order?

C # Programming Summary (12) breakpoint Continuation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.