用C#实现HTTP协议下的多线程文件传输
http://tech.ddvip.com 2006年08月02日 社区交流
本文详细介绍用C#实现HTTP协议下的多线程文件传输
一个列表框 listBox1 三个文本标签 label1-label3 三个文本框 textBox1-textBox3 一个开始接收按钮 button1 设计好的窗口如下图:

控件定义代码是:
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;
打开Form1的代码编辑器,增加如下的命名空间:
using System.Net;//网络功能
using System.IO;//流支持
using System.Threading ;//线程支持
增加如下的程序变量:
public bool[] threadw; //每个线程结束标志
public string[] filenamew;//每个线程接收文件的文件名
public int[] filestartw;//每个线程接收文件的起始位置
public int[] filesizew;//每个线程接收文件的大小
public string strurl;//接受文件的URL
public bool hb;//文件合并标志
public int thread;//进程数
定义一个HttpFile类,用于管理接收线程,其代码如下:
public class HttpFile
{
public Form1 formm;
public int threadh;//线程代号
public string filename;//文件名
public string strUrl;//接收文件的URL
public FileStream fs;
public HttpWebRequest request;
public System.IO.Stream ns;
public byte[] nbytes;//接收缓冲区
public int nreadsize;//接收字节数
public HttpFile(Form1 form,int thread)//构造方法
{
formm=form;
threadh=thread;
}
~HttpFile()//析构方法
{
formm.Dispose ();
}
public void receive()//接收线程
{
filename=formm.filenamew[threadh];
strUrl=formm.strurl;
ns=null;
nbytes= new byte[512];
nreadsize=0;
formm.listBox1 .Items .Add ("线程"+threadh.ToString ()+"开始接收");
fs=new FileStream (filename,System.IO.FileMode.Create);
try
{
request=(HttpWebRequest)HttpWebRequest.Create (strUrl);
//接收的起始位置及接收的长度
request.AddRange(formm.filestartw [threadh],
formm.filestartw [threadh]+formm.filesizew [threadh]);
ns=request.GetResponse ().GetResponseStream ();//获得接收流
nreadsize=ns.Read (nbytes,0,512);
while (nreadsize>0)
{
fs.Write (nbytes,0,nreadsize);
nreadsize=ns.Read (nbytes,0,512);
formm.listBox1 .Items .Add ("线程"+threadh.ToString ()+"正在接收");
}
fs.Close();
ns.Close ();
}
catch (Exception er)
{
MessageBox.Show (er.Message );
fs.Close();
}
formm.listBox1 .Items.Add ("进程"+threadh.ToString ()+"接收完毕!");
formm.threadw[threadh]=true;
}
}
来源:VCKBASE 作者:董海林 责编:豆豆技术应用