/ C#

C#限制网络传输速率

一个项目用到的,直接用的winsock来传输,不废话直接帖代码

using System.Net;
using System.Net.Sockets;  //上面这两个是socket必须的
using System.Threading;     //主要用sleep函数
using System.Diagnostics;  //计时器

public double SendVarData(Socket s, byte[] data, int rate)  //参数分别是socket实例,要传输的数据,限制的速度,单位是B
        {
            int total = 0;   //已传输的数据量
            int size = data.Length;  //数据
            int dataleft = size;  //未传输的数据大小
            int sent;
            int tmp;  //用于计算一个周期所传输的数据量
            double time;
            double totaltime = 0;   //传输总时间
            byte[] datasize = new byte[4];  //每次传输4B
            Stopwatch spwatch = new Stopwatch();  //新建一个计时器
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);
            while (total < size)  //当已传输的数据量小于总数据量
            {
                tmp = 0;  
                spwatch.Start();  //开始计时
                while (tmp < rate)  //当传输的数据量小于定义的速度时开始传送,数据量大于速度时跳出循环
                {
                    if (total + 4 < size)   //不是最后一次传输
                    {
                        sent = s.Send(data, total, 4, SocketFlags.None);
                        total += sent;
                        dataleft -= sent;
                        tmp += sent;
                    }
                    else  //最后一次传输
                    {
                        sent = s.Send(data, total, dataleft, SocketFlags.None);
                        total += sent;
                        dataleft -= sent;
                        tmp += sent;
                    }
                }
                spwatch.Stop();  //停止计时
                time = double.Parse(spwatch.Elapsed.TotalSeconds.ToString()) * 1000;  //转换成毫秒
                totaltime += time;
                spwatch.Reset();  //计时器清空
                if (time < 1000)  //如果总时间小于1秒
                {
                    Thread.Sleep(1000 – (int)time);  //停止传输
                }
            }
            return totaltime;
        }

C#限制网络传输速率
Share this