110,534
社区成员
发帖
与我相关
我的任务
分享
public class DownloadThread
{
private string saveFilePath;
private Uri downUrl;
private long block;
private int threadId = -1;
private long downLength;
private bool finish = false;
private FileDownloader downloader;
public DownloadThread(FileDownloader downloader, Uri downUrl, string saveFile, long block, long downLength, int threadId)
{
this.downUrl = downUrl;
this.saveFilePath = saveFile;
this.block = block;
this.downloader = downloader;
this.threadId = threadId;
this.downLength = downLength;
}
public void ThreadRun()
{
//task
Thread td = new Thread(new ThreadStart(() =>
{
Console.WriteLine(threadId.ToString() + " start " + downLength.ToString() + " " + block.ToString());
if (downLength < block)//未下载完成
{
try
{
int startPos = (int)(block * (threadId - 1) + downLength);//开始位置
int endPos = (int)(block * threadId - 1);//结束位置
Console.WriteLine("Thread " + this.threadId + " start download from position " + startPos + " and endwith " + endPos);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downUrl);
request.Referer = downUrl.ToString();
request.Method = "GET";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
request.AllowAutoRedirect = false;
request.ContentType = "application/octet-stream";
request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
request.Timeout = 10 * 1000;
request.AllowAutoRedirect = true;
request.AddRange(startPos, endPos);
//Console.WriteLine(request.Headers.ToString());
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebResponse wb = request.GetResponse();
using (Stream _stream = wb.GetResponseStream())
{
byte[] buffer = new byte[1024 * 50];
long offset = -1;
using (Stream threadfile = new FileStream(this.saveFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
threadfile.Seek(startPos, SeekOrigin.Begin);
while ((offset = _stream.Read(buffer, 0, buffer.Length)) != 0)
{
downloader.append(offset);
threadfile.Write(buffer, 0, (int)offset);
downLength += offset;
downloader.update(this.threadId, downLength);
}
threadfile.Close();
_stream.Close();
Console.WriteLine("Thread " + this.threadId + " download finish");
this.finish = true;
}
}
}
catch (Exception e)
{
this.downLength = -1;
Console.WriteLine("Thread " + this.threadId + ":" + e.Message);
}
}
else
{
Console.WriteLine(downLength);
}
}));
td.IsBackground = true;
td.Start();
}
/// <summary>
/// 下载是否完成
/// </summary>
/// <returns></returns>
public bool isFinish()
{
return finish;
}
/// <summary>
/// 已经下载的内容大小 ;return 如果返回值为-1,代表下载失败
/// </summary>
/// <returns></returns>
public long getDownLength()
{
return downLength;
}
}