RecDataList.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. //一个sequence对应一组的数据包的数据结构
  9. public class RecDataList
  10. {
  11. public long sequence { get; set; }//序列号
  12. //对应的存储包的List
  13. List<UdpPacket> RecudpPackets = new List<UdpPacket>();
  14. public int total { get; set; }
  15. public int dataLength { get; set; }
  16. public int remainder { get; set; }
  17. public byte[] DataBuffer = null;
  18. public RecDataList(UdpPacket udp)
  19. {
  20. this.sequence = udp.sequence;
  21. this.total = udp.total;
  22. this.dataLength = udp.dataLength;
  23. this.remainder = udp.remainder;
  24. if (DataBuffer == null)
  25. {
  26. DataBuffer = new byte[dataLength * (total - 1) + remainder];
  27. }
  28. }
  29. public RecDataList(long sequence, int total, int chunkLength, int remainder)
  30. {
  31. this.sequence = sequence;
  32. this.total = total;
  33. this.dataLength = chunkLength;
  34. this.remainder = remainder;
  35. if (DataBuffer == null)
  36. {
  37. DataBuffer = new byte[this.dataLength * (this.total - 1) + this.remainder];
  38. }
  39. }
  40. public void addPacket(UdpPacket p)
  41. {
  42. RecudpPackets.Add(p);
  43. }
  44. public Msg show()
  45. {
  46. if (RecudpPackets.Count == total)//表示已经收集满了
  47. {
  48. //重组数据
  49. foreach (UdpPacket udpPacket in RecudpPackets)
  50. {
  51. //偏移量
  52. int offset = (udpPacket.index - 1) * udpPacket.dataLength;
  53. Buffer.BlockCopy(udpPacket.data, 0, DataBuffer, offset, udpPacket.data.Length);
  54. }
  55. Msg rmsg = (Msg)SerializationUnit.DeserializeObject(DataBuffer);
  56. DataBuffer = null;
  57. RecudpPackets.Clear();
  58. return rmsg;
  59. }
  60. else
  61. {
  62. return null;
  63. }
  64. }
  65. public bool containskey(UdpPacket udp)
  66. {
  67. foreach (UdpPacket udpPacket in RecudpPackets)
  68. {
  69. if (udpPacket.index == udp.index)
  70. return true;
  71. }
  72. return false;
  73. }
  74. }
  75. }