Thursday, September 23, 2010

asp.net HTTP protocol to achieve multi-threaded file transfer under the

Many people have had to use the network or the Internet Express software download ant file through the Internet, the software can greatly speed up the Internet using file transfer speeds, reducing file transfer time. Why is there so much the software the magic of it? The main reason is that these software using multi-threaded downloads and HTTP technologies. If our own to write a program like this, and can quickly download files on the Internet, it must be very pleasant. Below I will talk about how to use the C # language support for multi-threaded download a program, you will see the network using C # language program is how easy it should be, from which we can understand C # language, a strong network capabilities.

First, tell us about HTTP protocol, HTTP which Hpyer Text Transfer Protocal the abbreviation, it is the most important modern Internet is a network protocol, hypertext transfer protocol in the TCP / IP application layer protocol is a connectionless oriented, simple and fast C / S structure of the agreement. The working process of the whole sub-HTTP connection, request, response, and disconnect the four steps. C # language on the HTTP protocol provides a good support in.
NET class library provides the WebRequest and WebResponse classes, these classes are included in the System.Net namespace, use of these two classes can implement many advanced networking features in this paper is to use multi-threaded file download two classes.
 WebRequest and WebResponse is the abstract base class, so the program can not be directly used as an object, must be inherited, the actual use, according to the URI in the URI prefix used parameters are the appropriate subclass, for this type of HTTP URI, HttpWebRequest and HttpWebResponse classes can be used to handle clients with the HTTP communication between the WEB server.

HttpWebRequest class implements a number of WEB server through HTTP file access advanced features. HttpWebRequest WebRequest class is defined on the properties and methods to provide support, HttpWebRequest will be sent to Internet resources, the value of public open HTTP header for the property, by the method or system settings, common property or method set by the HTTP header is: accept the by the Accept property is set, the connection from the Connection property and the KeepAlive property is set, Content-Length, the ContentLength property is set, Content-Type, set the ContentType property, range, set by the AddRange method. The actual use of the header information is correct set, delivered to the WEB server, WEB server to respond on request.

HttpWebResponse classes inherit from WebResponse class to deal specifically with the return from the WEB server HTTP response, this class implements a lot of ways, has many attributes, you can receive a comprehensive treatment of Internet information. In the HttpWebResponse class, for the most common HTTP header field, the properties are independent of their counterparts, the programmer can easily access these properties in the HTTP header field received in the packet of information used in this case to the HttpWebResponse class attribute: ContentLength only receive the content length.

With the above understanding, the following look at the usage of these two classes, to create a HttpWebRequest object, do not use the HttpWebRequest constructor directly, but to use the WebRequest.Create method to initialize a HttpWebRequest instance, such as:
HttpWebRequest HWR = (HttpWebRequest) WebRequest.Create ( http://www.163.com/ );

Created this object, you can HttpWebRequest properties, and set a lot of HTTP header field content, such as hwr.AddRange (100,1000); set up to receive the object in the range of 100-1000 bytes. HttpWebReques object using GetResponse () method will return a HttpWebResponse object to make HTTP return packets of information, need to use the HttpWebResponse the GetResponseStream () method returns a Stream object, you can read the HTTP return message, such as: First define a Strean object public System.IO.Stream ns; then ns = hwr.GetResponse (). GetResponseStream (); to create a Stream object. After more than ready to have a knowledge of the following design our multi-threaded download Internet files, first open Visual Studio.Net Integrated Development Environment, select "File", "New", "project", then select "Visual C # project" the wizard on the right list box select "Windows Application", enter the project name, such as in this case: httpftp, then select "OK" button, the wizard automatically generates a Windows Application project. First, open the window design design of the application window, add the following controls: 

A list box listBox1 three text labels label1-label3 three text boxes textBox1-textBox3 a start button button1 designed to receive the window below:
Control code is defined:
public System.Windows.Forms.ListBox listBox1; 
private System.Windows.Forms.Label label1; 
private System.Windows.Forms.TextBox textBox1 
private System.Windows.Forms.Button button1; 
private System.Windows.Forms.Label label2; 
private System.Windows.Forms.TextBox textBox2; 
private System.Windows.Forms.Label label3; 
private System.Windows.Forms.TextBox textBox3; 
private System.Windows.Forms.Label label4; 
private System.Windows.Forms.TextBox textBox4;

Open Form1 code editor, add the following namespaces:
using System.Net; / / network functions 
using System.IO; / / streaming support 
using System.Threading; / / thread support

The procedure to add the following variables:
public bool [] threadw; / / mark the end of each thread 
public string [] filenamew; / / each thread receives the file name 
public int [] filestartw; / / each thread receives the starting position of the file 
public int [] filesizew; / / receive the file size of each thread 
public string strurl; / / URL to accept the file 
public bool hb; / / files into mark 
public int thread; / / process number

Define a HttpFile class for managing receiving thread, the code is as follows:
public class HttpFile 
( 
public Form1 formm; 
public int threadh; / / thread code public string filename; / / file name public string strUrl; / / URL to receive the file 
public FileStream fs; 
public HttpWebRequest request; 
public System.IO.Stream ns; 
public byte [] nbytes; / / receive buffer public int nreadsize; / / Receive number of bytes public HttpFile (Form1 form, int thread) / / constructor ( 
formm = form; 
threadh = thread; 
) 
~ HttpFile () / / destructor ( 
formm.Dispose (); 
) 
public void receive () / / receiver thread ( 
filename = formm.filenamew [threadh]; 
strUrl = formm.strurl; 
ns = null; 
nbytes = new byte [512]; 
nreadsize = 0; 
formm.listBox1. Items. Add ("Thread" + threadh.ToString () + "started to receive"); 
fs = new FileStream (filename, System.IO.FileMode.Create); 
try 
( 
request = (HttpWebRequest) HttpWebRequest.Create (strUrl); 
/ / Receive the starting position and receive the length of the request.AddRange (formm.filestartw [threadh], 
formm.filestartw [threadh] + formm.filesizew [threadh]); 
ns = request.GetResponse (). GetResponseStream ();// get the received stream nreadsize = ns.Read (nbytes, 0,512); 
while (nreadsize> 0) 
( 
fs.Write (nbytes, 0, nreadsize); 
nreadsize = ns.Read (nbytes, 0,512); 
formm.listBox1. Items. Add ("Thread" + threadh.ToString () + "is received"); 
) 
fs.Close (); 
ns.Close (); 
) 
catch (Exception er) 
( 
MessageBox.Show (er.Message); 
fs.Close (); 
) 
formm.listBox1. Items.Add ("Process" + threadh.ToString () + "has been received!"); 
formm.threadw [threadh] = true; 
) 
)

Form1 class in the class and unified namespace, but not included in the Form1 class. The following defines the "Start Receive" button control the incident response function:
private void button1_Click (object sender, System.EventArgs e) 
( 
DateTime dt = DateTime.Now; / / start receiving time textBox1.Text = dt.ToString (); 
strurl = textBox2.Text. Trim (). ToString (); 
HttpWebRequest request; 
long filesize = 0; 
try 
( 
request = (HttpWebRequest) HttpWebRequest.Create (strurl); 
filesize = request.GetResponse (). ContentLength; / / get the length of the target file request.Abort (); 
) 
catch (Exception er) 
( 
MessageBox.Show (er.Message); 
) 
/ / Receive threads thread = Convert.ToInt32 (textBox4.Text. Trim (). ToString (), 10); 
/ / Initialize the array based on the number of threads threadw = new bool [thread]; 
filenamew = new string [thread]; 
filestartw = new int [thread]; 
filesizew = new int [thread];

/ / Calculated for each thread should receive the file size int filethread = (int) filesize / thread; / / evenly distributed int filethreade = filethread + (int) filesize% thread; / / remainder completed by the last thread / / for the array assignment for (int i = 0; i  
( 
threadw [i] = false; / / The initial state of each thread is false filenamew [i] = i.ToString ()+". dat "; / / each thread receives the temporary file file name if (i < thread-1) 
( 
filestartw [i] = filethread * i; / / the starting point of each thread to receive the file filesizew [i] = filethread-1; / / the length of each thread to receive the file) 
else 
( 
filestartw [i] = filethread * i; 
filesizew [i] = filethreade-1; 
) 
) 
/ / Define an array of threads to start receiving thread Thread [] threadk = new Thread [thread]; 
HttpFile [] httpfile = new HttpFile [thread]; 
for (int j = 0; j  
( 
httpfile [j] = new HttpFile (this, j); 
threadk [j] = new Thread (new ThreadStart (httpfile [j]. receive)); 
threadk [j]. Start (); 
) 
/ / Start the thread to receive the paper merged thread Thread hbth = new Thread (new ThreadStart (hbfile)); 
hbth.Start (); 
)

Hbfile threads merged file defined in the Form1 class, defined as follows:
public void hbfile () 
( 
while (true) / / wait ( 
hb = true; 
for (int i = 0; i  
( 
if (threadw [i] == false) / / there is not the end of the thread, waiting ( 
hb = false; 
Thread.Sleep (100); 
break; 
) 
) 
if (hb == true) / / all threads have ended, stop waiting 
( 
break; 
) 
) 
FileStream fs; / / start merging FileStream fstemp; 
int readfile; 
byte [] bytes = new byte [512]; 
fs = new FileStream (textBox3.Text. Trim (). ToString (), System.IO.FileMode.Create); 
for (int k = 0; k  
( 
fstemp = new FileStream (filenamew [k], System.IO.FileMode. Open); 
while (true) 
( 
readfile = fstemp.Read (bytes, 0,512); 
if (readfile> 0) 
( 
fs.Write (bytes, 0, readfile); 
) 
else 
( 
break; 
) 
) 
fstemp.Close (); 
) 
fs.Close (); 
DateTime dt = DateTime.Now; 
textBox1.Text = dt.ToString ();// end time MessageBox.Show ("been received !!!"); 
)

At this point, a multi-threaded download the program and you're done, pay attention to the local file name in the input when the input format should be as follows: "c: \ \ test \ \ httpftp \ \ bin \ \ d.htm", because "\" after the character in C # is an escape character, the number of threads is not the bigger the better, generally 5 threads on it, the program development environment in Visual Studio.Net 2002 and Windows xp operating system on the pass.

No comments:

Post a Comment