12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- namespace Team.Communicate.State
- {
- public class ServerBuffer
- {
- public Encoding Encoding { get; set; }
- public byte[] Splits { get; set; } = new byte[] { 0x13, 0x10 };
- private readonly MemoryStream _memoryStream;
- public ServerBuffer()
- {
- _memoryStream = new MemoryStream();
- }
- public void WriteBuffer(byte[] buffer, int offset, int length)
- {
- _memoryStream.Write(buffer, offset, length);
- }
- public async Task WriteBufferAsync(byte[] buffer, int offset, int length)
- {
- await _memoryStream.WriteAsync(buffer, offset, length);
- }
- public string GetBuffer()
- {
- var bufferList = new List<byte>();
- while (true)
- {
- var buffer = new byte[1];
- var length = _memoryStream.Read(buffer, 0, buffer.Length);
-
- bufferList.AddRange(buffer);
- var compareData =bufferList.ToArray().Reverse().Take(Splits.Length).Reverse().ToArray();
- var isSplits= Compare(compareData, Splits);
- if (isSplits)
- {
- return Encoding.GetString(buffer);
- }
- }
- }
- public async Task<string> GetBufferAsync()
- {
- var bufferList = new List<byte>();
- while (true)
- {
- var buffer = new byte[1];
- var length =await _memoryStream.ReadAsync(buffer, 0, buffer.Length);
- if (length==0)
- {
- await Task.Delay(10);
- await _memoryStream.FlushAsync();
- continue;
- }
- bufferList.AddRange(buffer);
- var compareData = bufferList.ToArray().Reverse().Take(Splits.Length).Reverse().ToArray();
- var isSplits = Compare(compareData, Splits);
- if (isSplits)
- {
- return Encoding.GetString(buffer);
- }
- }
- }
- private bool Compare(byte[] source, byte[] comparedData)
- {
- for (int i = 0; i < source.Length; i++)
- {
- if (comparedData[i] != source[i])
- {
- return false;
- }
- }
- return true;
- }
- }
- }
|