Esempio n. 1
0
        public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
        {
            CheckNotDisposed();
            ValidateBufferArgs(buffer, offset, length);

            if (!IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen);
            }

            // enough space left in buffer?
            var free = WriteBuffer.Capacity - WriteBuffer.Length;

            if (length > free)
            {
                ArraySegment <byte> bufSegment;
                WriteBuffer.TryGetBuffer(out bufSegment);
                await InnerTransport.WriteAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);

                WriteBuffer.SetLength(0);
            }

            // do the data even fit into the buffer?
            // Note we test for < instead of <= to avoid nonsense buffering
            if (length < WriteBuffer.Capacity)
            {
                await WriteBuffer.WriteAsync(buffer, offset, length, cancellationToken);

                return;
            }

            // write thru
            await InnerTransport.WriteAsync(buffer, offset, length, cancellationToken);
        }
        private async ValueTask ReadFrameAsync(CancellationToken cancellationToken)
        {
            await InnerTransport.ReadAllAsync(HeaderBuf, 0, HeaderSize, cancellationToken);

            int size = BinaryPrimitives.ReadInt32BigEndian(HeaderBuf);

            if ((0 > size) || (size > Configuration.MaxFrameSize))  // size must be in the range 0 to allowed max
            {
                throw new TTransportException(TTransportException.ExceptionType.Unknown, $"Maximum frame size exceeded ({size} bytes)");
            }
            UpdateKnownMessageSize(size + HeaderSize);

            ReadBuffer.SetLength(size);
            ReadBuffer.Seek(0, SeekOrigin.Begin);

            ArraySegment <byte> bufSegment;

            ReadBuffer.TryGetBuffer(out bufSegment);
            await InnerTransport.ReadAllAsync(bufSegment.Array, 0, size, cancellationToken);
        }
 private void InitWriteBuffer()
 {
     // Reserve space for message header to be put right before sending it out
     WriteBuffer.SetLength(HeaderSize);
     WriteBuffer.Seek(0, SeekOrigin.End);
 }