gpt4 book ai didi

c# - 使用套接字 tcp c# 计算发送文件的每秒速度和剩余时间

转载 作者:太空宇宙 更新时间:2023-11-03 14:07:10 24 4
gpt4 key购买 nike

如何计算每秒的速度,以及以秒为单位的剩余时间?我试过使用:

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
long prevSum = 0;
while (fileTransfer.busy) {
rate = (fileTransfer.sum - prevSum);
RateLabel(rate); //converting prevSum to (int)KB/SEC
if (rate != 0)
left = (fileTransfer.fileSize - fileTransfer.sum) / rate;
TimeSpan t = TimeSpan.FromSeconds(left);
timeLeftLabel(FormatRemainingText(rate, t)); //show how much left
prevSum = fileTransfer.sum;
Thread.Sleep(1000);
}
}

但是速率和剩余时间会永久上下波动(30MB/秒然后 5MB/秒)。

这是发送文件代码:

public static void sendFile(string filePath) {
// run the progres Form
Thread thFP = new Thread(fpRUN);
fileProgress fP = new fileProgress("Sending...");
thFP.Start(fP);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string fileName = Path.GetFileName(filePath);
byte[] fileData;
try {
//sending file name and file size to the server
busy = true;
fileSize = fs.Length;
byte[] fileDetial = null;
string detail = fileName + "," + fileSize.ToString();
fileDetial = Encoding.ASCII.GetBytes(detail);
client.Send(fileDetial);

//sending file data to the server
fileData = new byte[packetSize];
count = 0;
sum = 0;

fP.SizeLabel(fileSize); // tell the form the file size
while (sum < fileSize) {
fs.Seek(sum, SeekOrigin.Begin);
fs.Read(fileData, 0, fileData.Length);
count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
sum += count;
fP.ProgressBarFileHandler(sum,fileSize); //progressbar value
fP.SentLabel(sum); //tell the form how much sent
}
}
finally {
busy = false;
fs.Close();
fileData = null;
MessageBox.Show(string.Format("{0} sent successfully", fileName));
}
}

我该如何解决?有没有更好的方法来计算速度?

最佳答案

您可以对传输速度进行一些平滑处理,以避免值跳跃。参见 http://en.wikipedia.org/wiki/Moving_average一个选项。基本上计算一段时间内速度的某种平均值。

关于c# - 使用套接字 tcp c# 计算发送文件的每秒速度和剩余时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9029218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com