示例#1
0
    public override async Task <byte[]> ReceiveAsync(CancellationToken token = default)
    {
        while (true)
        {
            byte[] bytes;
            try
            {
                bytes = await Broadcast.ReceiveAsync(token).ConfigureAwait(false);
            }
            catch
            {
                _receivedSegmentsBuffer.Clear();
                throw;
            }

            Package package;
            try
            {
                package = (Package)_formatter.OneLineDeserialize(bytes);
            }
            catch (SerializationException)
            {
                continue;
            }


            if (_receivedSegmentsBuffer.ContainsKey(package.SequenceGuid))
            {
                _receivedSegmentsBuffer[package.SequenceGuid].AddSegment(package.Segment);

                if (!_receivedSegmentsBuffer[package.SequenceGuid].TryAssemble(out var assembledBytes))
                {
                    continue;
                }

                _receivedSegmentsBuffer.Remove(package.SequenceGuid, out _);
                return(assembledBytes);
            }

            if (package.SequenceLength == 1)
            {
                return(package.Segment.Payload);
            }

            var chain = new Chain(package.SequenceLength);
            chain.AddSegment(package.Segment);

            _receivedSegmentsBuffer.TryAdd(package.SequenceGuid, chain);
        }
    }