PacketQueue.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*********************************************************************************
  2. *Author: OnClick
  3. *Version: 0.0.1
  4. *UnityVersion: 2017.2.3p3
  5. *Date: 2019-03-14
  6. *Description: IFramework
  7. *History: 2018.11--
  8. *********************************************************************************/
  9. using System.Collections.Generic;
  10. namespace IFramework.Packets
  11. {
  12. class PacketQueue
  13. {
  14. private CycQueue<byte> _bucket = null;
  15. public PacketQueue(int maxCount)
  16. {
  17. _bucket = new CycQueue<byte>(maxCount);
  18. }
  19. public int count { get { return _bucket.Length; } }
  20. public bool Set(byte[] buffer, int offset, int size)
  21. {
  22. if (_bucket.Capacity - _bucket.Length < size)
  23. return false;
  24. for (int i = 0; i < size; ++i)
  25. {
  26. bool rt = _bucket.EnQueue(buffer[i + offset]);
  27. if (rt == false)
  28. return false;
  29. }
  30. return true;
  31. }
  32. public List<Packet> Get()
  33. {
  34. int _head = -1, _pos = 0;
  35. List<Packet> pkgs = null;
  36. again:
  37. _head = _bucket.DeSearchIndex(Packet.packFlag, _pos);
  38. if (_head == -1) return pkgs;
  39. int peek = _bucket.PeekIndex(Packet.packFlag, 1);
  40. if (peek >= 0)
  41. {
  42. _pos = 1;
  43. goto again;
  44. }
  45. //数据包长度
  46. int pkgLength = CheckCompletePackageLength(_bucket.Array, _head);
  47. if (pkgLength == 0) return pkgs;
  48. //读取完整包并移出队列
  49. byte[] array = _bucket.DeQueue(pkgLength);
  50. if (array == null) return pkgs;
  51. Packet _pkg = Packet.UnPackPacket(array, 0, array.Length);
  52. //解析
  53. if (_pkg != null)
  54. {
  55. if (pkgs == null) pkgs = new List<Packet>(2);
  56. pkgs.Add(_pkg);
  57. }
  58. if (_bucket.Length > 0)
  59. {
  60. _pos = 0;
  61. goto again;
  62. }
  63. return pkgs;
  64. }
  65. private unsafe int CheckCompletePackageLength(byte[] buff, int offset)
  66. {
  67. fixed (byte* src = buff)
  68. {
  69. int head = offset;
  70. int cnt = 0;
  71. byte flag = 0;
  72. do
  73. {
  74. if (*(src + head) == Packet.packFlag)
  75. {
  76. ++flag;
  77. if (flag == 2) return cnt + 1;
  78. }
  79. head = (head + 1) % _bucket.Capacity;
  80. ++cnt;
  81. }
  82. while (cnt <= _bucket.Length);
  83. cnt = 0;
  84. return cnt;
  85. }
  86. }
  87. public void Clear()
  88. {
  89. _bucket.Clear();
  90. }
  91. }
  92. }