前段时间, 公司要求做一个检测客户端网络上传/下载速率的问题,想来想去没什么好的方法做,最后用了一种不是很理想的方法实现,其原理就是上传时,从客户端POST 相应大小的数据包到服务器,计算这个过程完成所需的时间;下载也同样的道理,就是从服务器下载相应大小的数据包到客户端。
下面我就把代码共享下,供大家参考吧....
using System.Threading;
using System.IO;
using System.Net;
public class SpeedEntity
{
private const string LOCAL_FILE = @"C:\Temp\SpeedTest.tmp";
private const int FILE_SIZE = 102400;
private string strDownLoadFile = string.Empty;
private string strUpLoadFile = string.Empty;
/// <summary>
/// Download File
/// </summary>
public string DownLoadFile
{
get { return this.strDownLoadFile; }
set { this.strDownLoadFile = value; }
}
/// <summary>
/// Upload File
/// </summary>
public string UpLoadFile
{
get { return this.strUpLoadFile; }
set { this.strUpLoadFile = value; }
}
/// <summary>
///
/// </summary>
/// <param name="p_downLoadFile"></param>
/// <param name="p_upLoadFile"></param>
public SpeedEntity(string p_downLoadFile, string p_upLoadFile)
{
this.strDownLoadFile = p_downLoadFile;
this.strUpLoadFile = p_upLoadFile;
}
// NetWork DownLoad Speed Check
public double DownloadSpeedCheck()
{
// this is a test file in download server, the is must config and the fils size is 100K.
//string strDistFile = @"http://192.168.0.104:86/DownLoadFile/SpeedFile.rar";
string strDistFile = strDownLoadFile;
// Begin Time
DateTime dtStart = DateTime.Now;
WebClient wc = new WebClient();
wc.DownloadFile(strDistFile, LOCAL_FILE);
// End Time
DateTime dtEnd = DateTime.Now;
TimeSpan ts = new TimeSpan();
ts = dtEnd - dtStart;
double intMinSecond = ts.TotalMilliseconds;
FileInfo file = new FileInfo(LOCAL_FILE);
double downSpeedNum = file.Length * 1000.0 / intMinSecond;
System.Threading.Thread.Sleep(1000);
return downSpeedNum;
}
// Check Upload Speed
public double UploadSpeedCheck()
{
if (!File.Exists(LOCAL_FILE))
this.DownloadSpeedCheck();
// this is server request upload file , the is must config and the fils size is 100K.
//string strDistServer = @"http://192.168.0.104:86/UploadFileWeb/ClientFileUpload.aspx";
string strDistServer = strUpLoadFile;
// Begin Time
DateTime dtStart = DateTime.Now;
WebClient wc = new WebClient();
byte[] responseArray = wc.UploadFile(strDistServer, "POST", LOCAL_FILE);
// EndTime
DateTime dtEnd = DateTime.Now;
TimeSpan ts = new TimeSpan();
ts = dtEnd - dtStart;
double intMinSecond = ts.TotalMilliseconds;
FileInfo file = new FileInfo(LOCAL_FILE);
double uploadSpeedNum = file.Length * 1000.0 / intMinSecond;
System.Threading.Thread.Sleep(1000);
return uploadSpeedNum;
}
// Get BPS/Sec Format Information
public string BpsToString(double bps)
{
string[] m = new string[] { "bytes", "Kbps", "Mbps", "Gbps", "TB", "PB", "EB", "ZB", "YB" }; //dreaming of YB/sec
int i = 0;
while (bps >= 0.9 * 1024)
{
bps /= 1024;
i++;
}
return String.Format("{0:0.00} {1}", bps, m[i]);
}
}