public async UniTask <byte> ReceiveAsync(MemoryStream buffer) { // wait for a message await MessageCount.WaitAsync(); buffer.SetLength(0); reader.buffer = writer.ToArraySegment(); ArraySegment <byte> data = reader.ReadBytesAndSizeSegment(); if (data.Count == 0) { throw new EndOfStreamException(); } buffer.SetLength(0); buffer.Write(data.Array, data.Offset, data.Count); if (reader.Position == reader.Length) { // if we reached the end of the buffer, reset the buffer to recycle memory writer.SetLength(0); reader.Position = 0; } return(0); }
public void TestWritingBytesAndReadingSegment() { byte[] data = { 1, 2, 3 }; NetworkWriter writer = new NetworkWriter(); writer.WriteBytesAndSize(data); NetworkReader reader = new NetworkReader(writer.ToArray()); ArraySegment<byte> deserialized = reader.ReadBytesAndSizeSegment(); Assert.That(deserialized.Count, Is.EqualTo(data.Length)); for (int i = 0; i < data.Length; ++i) Assert.That(deserialized.Array[deserialized.Offset + i], Is.EqualTo(data[i])); }
public void TestWritingSegmentAndReadingSegment() { byte[] data = { 1, 2, 3, 4 }; // [2, 3] ArraySegment<byte> segment = new ArraySegment<byte>(data, 1, 1); NetworkWriter writer = new NetworkWriter(); writer.WriteBytesAndSizeSegment(segment); NetworkReader reader = new NetworkReader(writer.ToArray()); ArraySegment<byte> deserialized = reader.ReadBytesAndSizeSegment(); Assert.That(deserialized.Count, Is.EqualTo(segment.Count)); for (int i = 0; i < segment.Count; ++i) Assert.That(deserialized.Array[deserialized.Offset + i], Is.EqualTo(segment.Array[segment.Offset + i])); }