using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ToolsClassLibrary.UDP { /// /// UDP数据包分割器 /// public static class UdpPacketSplitter { public static ICollection Split(Msg message) { byte[] datagram = null; try { datagram = SerializationUnit.SerializeObject(message); } catch (Exception e) { //AddTalkMessage("数据转型异常"); } //产生一个序列号,用来标识包数据属于哪一组 Random Rd = new Random(); long SequenceNumber = Rd.Next(88888, 999999); ICollection udpPackets = UdpPacketSplitter.Split(SequenceNumber, datagram, 10240, message.destinationIP, message.port); return udpPackets; } /// /// 分割UDP数据包 /// /// UDP数据包所持有的序号 /// 被分割的UDP数据包 /// 分割块的长度 /// /// 分割后的UDP数据包列表 /// public static ICollection Split(long sequence, byte[] datagram, int chunkLength, string desip, int port) { if (datagram == null) throw new ArgumentNullException("datagram"); List packets = new List(); int chunks = datagram.Length / chunkLength; int remainder = datagram.Length % chunkLength; int total = chunks; if (remainder > 0) total++; for (int i = 1; i <= chunks; i++) { byte[] chunk = new byte[chunkLength]; Buffer.BlockCopy(datagram, (i - 1) * chunkLength, chunk, 0, chunkLength); packets.Add(new UdpPacket(sequence, total, i, chunk, chunkLength, remainder, desip, port)); } if (remainder > 0) { int length = datagram.Length - (chunkLength * chunks); byte[] chunk = new byte[length]; Buffer.BlockCopy(datagram, chunkLength * chunks, chunk, 0, length); packets.Add(new UdpPacket(sequence, total, total, chunk, chunkLength, remainder, desip, port)); } return packets; } } }