我现在想做一个简单的下载工具,就是制定一个下载的url地址。然后自己在程序中输入50k每秒。那么我这个程序的下载速度就被限制到50k每秒了。【不管是1个线程下载还是多个线程下载,总之就是所有的线程下载和就是 50k每秒】。这个如何实现呢?

解决方案 »

  1.   

    从网上来的,楼主也可以google一下啊protected void DoDownLoad(long lngSpeed)
    {
    Page.Response.Clear();
    bool success = ResponseFile(Page.Request, Page.Response, "下载时显示的名称.rar", "E:\\WWWROOT\\files\\www.linjunjie.net.rar", lngSpeed);
    if (!success)
    {
    Response.Write("下载文件出错!");
    }
    else
    {
    Response.Write("下载文件成功!");
    }
    Page.Response.End();
    }public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
    try
    {
    FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    BinaryReader br = new BinaryReader(myFile);
    try
    {
    _Response.AddHeader("Accept-Ranges", "bytes");
    _Response.Buffer = false;
    long fileLength = myFile.Length;
    long startBytes = 0;
    double pack = 1024;
    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
    if (_Request.Headers["Range"] != null)
    {
    _Response.StatusCode = 206;
    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
    startBytes = Convert.ToInt64(range[1]);
    }
    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
    _Response.AddHeader("Connection", "Keep-Alive");
    _Response.ContentType = "application/octet-stream";
    _Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
    for (int i = 0; i < maxCount; i++)
    {
    if (_Response.IsClientConnected)
    {
    _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
    Thread.Sleep(sleep);
    }
    else
    {
    i = maxCount;
    }
    }
    }
    catch (Exception e4)
    {
    System.Web.HttpContext.Current.Response.Write(e4.Message);
    return false;
    }
    finally
    {
    br.Close();
    myFile.Close();
    }
    }
    catch (Exception e3)
    {
    System.Web.HttpContext.Current.Response.Write(e3.Message);
    return false;
    }
    return true;
    }protected void Button1_Click(object sender, EventArgs e)
    {
    DoDownLoad(5 * 1024);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
    DoDownLoad(50 * 1024);
    }
      

  2.   

    /// <summary>
    /// 输出硬盘文件,提供下载
    /// </summary>     
    /// <param name="context">HttpContext对象</param>
    /// <param name="_fullPath">要下载的文件的完整路径</param>
    /// <param name="_speed">每秒允许下载的字节数</param>
    /// <returns>是否成功</returns>
    public static bool ResponseFile(HttpContext context, string _fullPath, long _speed) {
        HttpRequest _Request = context.Request;
        HttpResponse _Response = context.Response;
        string strFileName = new FileInfo(_fullPath).Name;
        try {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;
     
                int pack = 10240; //10K bytes       进行拆包,每包大小
                int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;       //pack/_speed 每个包发送速度/秒 总的意思:发包频率
                if (_Request.Headers["Range"] != null) {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0) {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
                for (int i = 0; i < maxCount; i++) {
                    if (_Response.IsClientConnected) {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        _Response.Flush();
                        System.Threading.Thread.Sleep(sleep);              //线程休息sleep毫秒后继续
                    } else {
                        i = maxCount;
                    }
                }
            } catch {
                return false;
            } finally {
                br.Close();
                myFile.Close();
            }
        } catch {
            return false;
        }
        return true;
    }