WinForm客户端限速下载(C#限速下载)

时间:2023-03-09 07:54:48
WinForm客户端限速下载(C#限速下载)

  最近由于工作需要,需要开发一个能把服务器上的文件批量下载下来本地保存,关键是要实现限速下载,如果全速下载会影响服务器上的带宽流量。本来我最开始的想法是在服务器端开发一个可以从源头就限速下载的Api端口,可是找了半天没有相关的实现代码,后来好不容易找到一个,却只能只能在WebForm的HttpResponse上实现,我用的是webApi的HttpResponseMessage实现不了把流文件一点一点输出。(可能是我对相关协议还不清楚,所以把参考链接给出,如果有知道怎么在WebApi框架服务器端限速下载的童鞋,麻烦告诉我一下:https://www.cnblogs.com/ghd258/articles/260236.html)

  后来没办法,把思路改为直接在下载的客户端限制下载速度,主体思路就是每下载N字节后就计算平均下载速度,如果平均下载速度快了,就暂停下载,通过拉长下载时间来实现降低平均下载速度。下面贴出主要核心的下载代码:

  欢迎批评指正,写的比较匆忙!

         /// <summary>
/// 下载并保存文件
/// </summary>
/// <param name="waveID">主键</param>
/// <param name="saveName">文件名</param>
/// <param name="folderName">文件夹名称</param>
/// <param name="speed">限速</param>
/// <param name="callBackMethod">回调</param>
/// <returns></returns>
public int DownloadAndSaveAs(string waveID, string saveName, string folderName, int speed, SetTextCallBack callBackMethod)
{
if (string.IsNullOrWhiteSpace(waveID))
return -; using (WebClient webClient = new WebClient())
{
try
{
string savePath = "C:\\"+ folderName+ "\\";
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
using (FileStream fs = new FileStream(savePath + saveName, FileMode.Create, FileAccess.Write))
{
try
{
string url =string.Format( "Http://www.文件下载路径.com?waveID={0}",waveID);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
{
int blockSize = ;//每次读取的字节数,不固定
byte[] buffer = new byte[blockSize];
int read = ;//每次读取后返回的下一次 的坐标位置,当没有数据时是-1
long total_read = ;//已经读取到的字节数总和
DateTime begin = DateTime.Now; while ((read = stream.Read(buffer, , buffer.Length)) > )
{
total_read += blockSize;
double totalSeconds=DateTime.Now.Subtract(begin).TotalSeconds;
double byteper = total_read / totalSeconds;//[字节总数]除以[所花时间总秒数]=每秒获取的字节数 if (double.IsInfinity(byteper))
{
//排除byteper正无穷的情况
fs.Write(buffer, , buffer.Length);
continue;
}
else
{
double speedPer = byteper / ;//单位转换得到千字节
if (speedPer >= speed)//speed为我们设置的限速字段,单位kb
{
//下面的逻辑是通过:现实速度-限速=超速部分,通过超速部分计算要让线程休眠时长。
double tempData = speedPer - speed;
if (tempData < ) tempData = ;
int sleepMS = Convert.ToInt32(tempData * ( / speed) + );//1000除以速度得到“每KB消耗的毫秒数”,100是一个自定义值,更好的限制下载速度
if (sleepMS > )
{
sleepMS = ;//有时下载峰值会超大,导致休眠很长,所以强制设为最多休眠一秒。
}
else
{
if (total_read % == )//取模只用于降低重写文本框的频率
{
if (callBackMethod != null)
{
callBackMethod(string.Format("下载速度:{0}KB/s,休眠周期:{1} ms", speedPer.ToString("F"), sleepMS));
}
}
}
System.Threading.Thread.Sleep(sleepMS); // 休眠实现限速
}
else
{
if (total_read % == )
{
if (callBackMethod != null)
{
callBackMethod(string.Format("下载速度:{0}KB/s,休眠周期:{1} ms", speedPer.ToString("F"), ));
}
} }
fs.Write(buffer, , buffer.Length);
}
}
}
return ;
}
catch (Exception e)
{
return -;
}
}
}
catch (Exception ex)
{
return -;
}
}
}

本文参考了,但做了优化:http://blog.useasp.net/archive/2016/03/10/limit-download-speed-in-dotnet-httpwebresponse.aspx