如何计算每秒千字节的传输速率,我使用秒表但它不起作用,因为它给我一个关于零的错误(计数/ 0)
public void sendFile(string filePath)
{
Stopwatch stopWatch = new Stopwatch();
FileInfo file = new FileInfo(filePath);
try
{
int fileSize = (int)file.Length;
Program.mainForm.MaxProgressBarHandler(fileSize);
byte[] fileDetial;
string detail = file.Name + "," + fileSize.ToString();
fileDetial = Encoding.ASCII.GetBytes(detail);
client.Send(fileDetial);
byte[] fileData = new byte[fileSize];
int count;
int sum = 0;
file.OpenRead().Read(fileData, 0, fileSize);
while (sum < fileSize)
{
stopWatch.Restart();
if (fileSize - sum < packetSize)
{
count = client.Send(fileData, sum, fileSize - sum, SocketFlags.None);
Program.mainForm.UpdateProgressBarHandler(count);
}
else
{
count = client.Send(fileData, sum, packetSize, SocketFlags.None);
Program.mainForm.UpdateProgressBarHandler(count);
}
stopWatch.Stop();
sum += count;
Program.mainForm.AppendLabel(((fileSize * 8) / stopWatch.ElapsedMilliseconds).ToString());
Console.WriteLine(sum + "of" + fileSize + "sent");
}
}
finally
{
Console.WriteLine("sent");
CloseClient();
}
}
请帮帮我=)
答案 0 :(得分:1)
对于问题的第一部分,请查看此Joel On Software Forum Thread。它不是特定的.Net相关,而是直接处理使用TCP传输文件。
至于第二部分,由于我没有完整的代码,所以我无法理解为什么stopWatch.ElapsedMilliseconds
等于零。我的猜测是没有数据要传输。您可以尝试做这样的事情以避免除以零错误。
if (stopWatch.ElapsedMilliseconds != 0)
Program.mainForm.AppendLabel(((fileSize * 8) / stopWatch.ElapsedMilliseconds).ToString());
虽然我可能有1秒的计时器,并使sum
成为一个类范围的变量并每隔一秒更新一次标签,例如:
public partial class Form1 : Form
{
int sum = 0;
int seconds = 0;
...
private void timer1_Tick(object sender, EventArgs e)
{
seconds += 1;
Program.mainForm.AppendLabel(((sum * 8) / seconds).ToString());
}
并在完成转帐时重置它们。
....
finally
{
timer1.Stop();
sum = 0;
seconds = 0
Console.WriteLine("sent");
CloseClient();
}