ReceivedBuffer.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using CommonLang.IO;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. namespace CommonNetwork.Utils
  8. {
  9. public class ReceiveBuffer
  10. {
  11. private MemoryStream stream;
  12. private long w_pos;
  13. public ReceiveBuffer(int capacity)
  14. {
  15. this.stream = new MemoryStream(capacity);
  16. this.w_pos = 0;
  17. }
  18. public MemoryStream Stream { get { return stream; } }
  19. public long Remaining
  20. {
  21. get
  22. {
  23. return w_pos - stream.Position;
  24. }
  25. }
  26. /// <summary>
  27. /// 向缓冲区写入数据
  28. /// </summary>
  29. /// <param name="data"></param>
  30. /// <param name="offset"></param>
  31. /// <param name="count"></param>
  32. public void Put(byte[] data, int offset, int count)
  33. {
  34. long oldpos = stream.Position;
  35. try
  36. {
  37. stream.Position = w_pos;
  38. IOUtil.WriteToEnd(stream, data, offset, count);
  39. w_pos += count;
  40. }
  41. finally
  42. {
  43. stream.Position = oldpos;
  44. }
  45. }
  46. public void Begin()
  47. {
  48. stream.Position = 0;
  49. }
  50. /// <summary>
  51. /// 将读取的数据制空
  52. /// </summary>
  53. public void Over()
  54. {
  55. if (stream.Position > 0 )
  56. {
  57. if (stream.Position == w_pos)
  58. {
  59. stream.Position = 0;
  60. w_pos = 0;
  61. }
  62. else if (stream.Position < w_pos)
  63. {
  64. int lp = (int)stream.Position;
  65. int ep = (int)w_pos;
  66. int rm = ep - lp;
  67. byte[] buffer = stream.GetBuffer();
  68. // 将后半段向前移动
  69. int cc = Math.Min(lp, rm);
  70. System.Buffer.BlockCopy(buffer, lp, buffer, 0, cc);
  71. if (lp == cc && rm > 0)
  72. {
  73. // 如果后半段还有更多
  74. int c2 = cc << 1;
  75. System.Buffer.BlockCopy(buffer, c2, buffer, lp, ep - c2);
  76. }
  77. stream.Position = 0;
  78. w_pos -= lp;
  79. }
  80. }
  81. }
  82. }
  83. }