internal class Program
{
static async Task Main(string[] args)
{
string msg = "123456789";
byte[] bb = Encoding.UTF8.GetBytes(msg);
byte[] newData = GetResponse(bb);
ReciveFullPacketEvent += Program_ReciveFullPacketEvent;
Test(newData);
while (true)
{
byte[] aa = newData.Take(2).ToArray();
Test(aa);
await Task.Delay(1000);
byte[] cc = newData.Skip(2).ToArray();
Test(cc);
}
Console.ReadKey();
}
private static void Program_ReciveFullPacketEvent(byte[] arg1, byte[] arg2)
{
string res = Encoding.UTF8.GetString(arg2);
Console.WriteLine(res);
}
static List<byte> cache = new List<byte>();
static public event Action<byte[], byte[]>? ReciveFullPacketEvent;
static int _headerSize = 4;
public static void Revice(byte[] bb)
{
cache.AddRange(bb);
}
/// <summary>
/// 测试4字节包头 处理数据
/// </summary>
/// <param name="bb"></param>
public static void Test(byte[] bb)
{
Revice(bb);
do
{
if (cache.Count < _headerSize)
{
break;
}
var header = cache.GetRange(0, _headerSize).ToArray();
var bodySize = BitConverter.ToInt32(header, 0);
var fullSize = bodySize + _headerSize;
if (cache.Count < fullSize)
{
break;
}
if (cache.Count >= fullSize)
{
var bodyData = cache.GetRange(_headerSize, bodySize).ToArray();//真正的包体数据
ReciveFullPacketEvent?.Invoke(header, bodyData);//处理数据
cache.RemoveRange(0, fullSize);//删除已经处理的数据
if (cache.Count == 0)
{
break;
}
}
} while (true);
}
public static byte[] GetResponse(byte[] data)
{
List<byte> list = new List<byte>();
byte[] collection = BitConverter.GetBytes((uint)data.Length).ToArray();
list.AddRange(collection);
list.AddRange(data);
return list.ToArray();
}
}