コード例 #1
0
        protected override void Encode(IChannelHandlerContext context, IMessage message, List <object> output)
        {
            IByteBuffer buffer = null;

            try
            {
                //int size = message.CalculateSize();
                //if (size == 0)
                //{
                //    return;
                //}
                //todo: Implement ByteBufferStream to avoid allocations.
                buffer = Unpooled.WrappedBuffer(VarMessageMap.GetMessageType(message), message.ToByteArray());
                output.Add(buffer);
                buffer = null;
            }
            catch (Exception exception)
            {
                throw new CodecException(exception);
            }
            finally
            {
                buffer?.Release();
            }
        }
コード例 #2
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List <object> output)
        {
            int length = message.ReadableBytes;

            if (length <= 0)
            {
                return;
            }
            Stream inputStream = null;

            try
            {
                short messageType = message.ReadShort();
                length -= 2;
                CodedInputStream codedInputStream;
                if (message.IoBufferCount == 1)
                {
                    ArraySegment <byte> bytes = message.GetIoBuffer(message.ReaderIndex, length);
                    codedInputStream = new CodedInputStream(bytes.Array, bytes.Offset, length);
                }
                else
                {
                    inputStream      = new ReadOnlyByteBufferStream(message, false);
                    codedInputStream = new CodedInputStream(inputStream);
                }

                //
                // Note that we do not dispose the input stream because there is no input stream attached.
                // Ideally, it should be disposed. BUT if it is disposed, a null reference exception is
                // thrown because CodedInputStream flag leaveOpen is set to false for direct byte array reads,
                // when it is disposed the input stream is null.
                //
                // In this case it is ok because the CodedInputStream does not own the byte data.
                //
                IMessage decoded = VarMessageMap.GetMessageParser(messageType).ParseFrom(codedInputStream);
                if (decoded != null)
                {
                    output.Add(decoded);
                }
            }
            catch (Exception exception)
            {
                throw new CodecException(exception);
            }
            finally
            {
                inputStream?.Dispose();
            }
        }