Udp分包过程(C#)

Send与SendTo以及Receive与Receivefrom之间的区别?

一般情况下:

Send、Receive用于TCP

SendTo、Receivefrom用于UDP


Udp发送超大文件一般采用分包发送的方式

Udp分包数据量的上限:  65k
                 
  

   #region 分包处理
        public static ICollection<UdpPacket> Split( byte[] datagram, int chunkLength)
        {
     
            string FILE = "First";//第一个分包的标识
            string Mid= "Mid";    //后续分包  的标识
            if (datagram == null)
                throw new ArgumentNullException("datagram");
            //存储所有的数据包
            List<UdpPacket> packets = new List<UdpPacket>();
            //完整的UDP数据包
            int chunks = datagram.Length / chunkLength;
            //最后一个不完整的数据包的数据量
            int remainder = datagram.Length % chunkLength;

            //判断最后一个数据包,计算总的数据包
            int total = chunks;
            if (remainder > 0) total++;
           //进行分包,区别对待第一个包和后续包
            //遍历所有的完整的UDP数据包       
                for (int i = 1; i <= chunks; i++)
                { 
                byte[] chunk=new byte[chunkLength];
                Buffer.BlockCopy(datagram,(i-1)*chunkLength,chunk,0,chunkLength);
                //第一个分包
                if (i == 1)
                {
                    packets.Add(new UdpPacket(FILE,total, i, chunk, chunkLength, remainder));
                }
               //后续分包标识
                    else
                    packets.Add(new UdpPacket(Mid, total, i, chunk, chunkLength, remainder));

                }
            //最后一个分包
                if (remainder > 0)
                {
                  
                 
                    if (total != 1)
                    {
                        int length = datagram.Length - (chunkLength * chunks);
                        byte[] chunk = new byte[length];
                        Buffer.BlockCopy(datagram, chunks * chunkLength, chunk, 0, length);
                        packets.Add(new UdpPacket(Mid, total, total, chunk, chunkLength, remainder));
                    }
                    else
                    {
                        int length = datagram.Length - (chunkLength * chunks);
                        byte[] chunk = new byte[length];
                        Buffer.BlockCopy(datagram, 0, chunk, 0, length);
                        packets.Add(new UdpPacket(FILE, total, total, chunk, chunkLength, remainder));                       
                    }
                   
                }
                 
                return packets;
        }
         #endregion


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值