计算每秒,剩余时间使用套接字TCP C#发送文件的速度 [英] Calculate speed per sec and time left of sending a file using sockets tcp c#

查看:261
本文介绍了计算每秒,剩余时间使用套接字TCP C#发送文件的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算每秒的速度,并留在秒的时候?我试着用:

How can I calculate the speed per sec, and the time left in sec? I've tried to use:

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 /秒)永久。

but the rate and the time left goes up and down like (30MB/sec then 5MB/sec) permanently.

这是发送文件代码:

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));
    }
}



我怎样才能解决呢?有没有更好的方法来计算的速度?

How can I fix that? Is there a better way to calculate the speed?

推荐答案

在表单构造

Timer timer1 = new Time();
public Form1()
    {
        InitializeComponent();
        this.timer1.Enabled = true;
        this.timer1.Interval = 1000;
        this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
    }

或从工具箱中添加它并设置之前的值

or add it from toolbox and set the previous values

结果发送的字节的总和应该是公开的,以便我们的方法能得到它的值每秒


the sum of sent bytes should be public so our method can get its value every second

    long sentBytes = 0;      //the sent bytes that updated from sending method
    long prevSentBytes = 0;   //which references to the previous sentByte
    double totalSeconds = 0;   //seconds counter to show total time .. it increases everytime the timer1 ticks.
    private void timer1_Tick(object sender, EventArgs e)
    {
        long speed = sentBytes - prevSentBytes ;  //here's the Transfer-Rate or Speed
        prevSentBytes = sentBytes ;
        labelSpeed.Text = CnvrtUnit(speed) + "/S";   //display the speed like (100 kb/s) to a label
        if (speed > 0)                //considering that the speed would be 0 sometimes.. we avoid dividing on 0 exception
        {
            totalSeconds++;     //increasing total-time
            labelTime.Text = TimeToText(TimeSpan.FromSeconds((sizeAll - sumAll) / speed));
            //displaying time-left in label
            labelTotalTime.Text = TimeToText(TimeSpan.FromSeconds(totalSeconds));
            //displaying total-time in label
        }
    }

    private string TimeToText(TimeSpan t)
    {
        return string.Format("{2:D2}:{1:D2}:{0:D2}", t.Seconds, t.Minutes, t.Hours);
    }

    private string CnvrtUnit(long source)
    {
        const int byteConversion = 1024;
        double bytes = Convert.ToDouble(source);

        if (bytes >= Math.Pow(byteConversion, 3)) //GB Range
        {
            return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 3), 2), " GB");
        }
        else if (bytes >= Math.Pow(byteConversion, 2)) //MB Range
        {
            return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 2), 2), " MB");
        }
        else if (bytes >= byteConversion) //KB Range
        {
            return string.Concat(Math.Round(bytes / byteConversion, 2), " KB");
        }
        else //Bytes
        {
            return string.Concat(bytes, " Bytes");
        }
    }

这篇关于计算每秒,剩余时间使用套接字TCP C#发送文件的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆