UdpPacketSplitter.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ToolsClassLibrary.UDP
  7. {
  8. /// <summary>
  9. /// UDP数据包分割器
  10. /// </summary>
  11. public static class UdpPacketSplitter
  12. {
  13. public static ICollection<UdpPacket> Split(Msg message)
  14. {
  15. byte[] datagram = null;
  16. try
  17. {
  18. datagram = SerializationUnit.SerializeObject(message);
  19. }
  20. catch (Exception e)
  21. {
  22. //AddTalkMessage("数据转型异常");
  23. }
  24. //产生一个序列号,用来标识包数据属于哪一组
  25. Random Rd = new Random();
  26. long SequenceNumber = Rd.Next(88888, 999999);
  27. ICollection<UdpPacket> udpPackets = UdpPacketSplitter.Split(SequenceNumber, datagram, 10240, message.destinationIP, message.port);
  28. return udpPackets;
  29. }
  30. /// <summary>
  31. /// 分割UDP数据包
  32. /// </summary>
  33. /// <param name="sequence">UDP数据包所持有的序号</param>
  34. /// <param name="datagram">被分割的UDP数据包</param>
  35. /// <param name="chunkLength">分割块的长度</param>
  36. /// <returns>
  37. /// 分割后的UDP数据包列表
  38. /// </returns>
  39. public static ICollection<UdpPacket> Split(long sequence, byte[] datagram, int chunkLength, string desip, int port)
  40. {
  41. if (datagram == null)
  42. throw new ArgumentNullException("datagram");
  43. List<UdpPacket> packets = new List<UdpPacket>();
  44. int chunks = datagram.Length / chunkLength;
  45. int remainder = datagram.Length % chunkLength;
  46. int total = chunks;
  47. if (remainder > 0) total++;
  48. for (int i = 1; i <= chunks; i++)
  49. {
  50. byte[] chunk = new byte[chunkLength];
  51. Buffer.BlockCopy(datagram, (i - 1) * chunkLength, chunk, 0, chunkLength);
  52. packets.Add(new UdpPacket(sequence, total, i, chunk, chunkLength, remainder, desip, port));
  53. }
  54. if (remainder > 0)
  55. {
  56. int length = datagram.Length - (chunkLength * chunks);
  57. byte[] chunk = new byte[length];
  58. Buffer.BlockCopy(datagram, chunkLength * chunks, chunk, 0, length);
  59. packets.Add(new UdpPacket(sequence, total, total, chunk, chunkLength, remainder, desip, port));
  60. }
  61. return packets;
  62. }
  63. }
  64. }