ServerBuffer.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Team.Communicate.State
  9. {
  10. public class ServerBuffer
  11. {
  12. public Encoding Encoding { get; set; }
  13. public byte[] Splits { get; set; } = new byte[] { 0x13, 0x10 };
  14. private readonly MemoryStream _memoryStream;
  15. public ServerBuffer()
  16. {
  17. _memoryStream = new MemoryStream();
  18. }
  19. public void WriteBuffer(byte[] buffer, int offset, int length)
  20. {
  21. _memoryStream.Write(buffer, offset, length);
  22. }
  23. public async Task WriteBufferAsync(byte[] buffer, int offset, int length)
  24. {
  25. await _memoryStream.WriteAsync(buffer, offset, length);
  26. }
  27. public string GetBuffer()
  28. {
  29. var bufferList = new List<byte>();
  30. while (true)
  31. {
  32. var buffer = new byte[1];
  33. var length = _memoryStream.Read(buffer, 0, buffer.Length);
  34. bufferList.AddRange(buffer);
  35. var compareData =bufferList.ToArray().Reverse().Take(Splits.Length).Reverse().ToArray();
  36. var isSplits= Compare(compareData, Splits);
  37. if (isSplits)
  38. {
  39. return Encoding.GetString(buffer);
  40. }
  41. }
  42. }
  43. public async Task<string> GetBufferAsync()
  44. {
  45. var bufferList = new List<byte>();
  46. while (true)
  47. {
  48. var buffer = new byte[1];
  49. var length =await _memoryStream.ReadAsync(buffer, 0, buffer.Length);
  50. if (length==0)
  51. {
  52. await Task.Delay(10);
  53. await _memoryStream.FlushAsync();
  54. continue;
  55. }
  56. bufferList.AddRange(buffer);
  57. var compareData = bufferList.ToArray().Reverse().Take(Splits.Length).Reverse().ToArray();
  58. var isSplits = Compare(compareData, Splits);
  59. if (isSplits)
  60. {
  61. return Encoding.GetString(buffer);
  62. }
  63. }
  64. }
  65. private bool Compare(byte[] source, byte[] comparedData)
  66. {
  67. for (int i = 0; i < source.Length; i++)
  68. {
  69. if (comparedData[i] != source[i])
  70. {
  71. return false;
  72. }
  73. }
  74. return true;
  75. }
  76. }
  77. }