コード例 #1
0
 protected override void ChannelRead0(IChannelHandlerContext ctx, byte[] msg)
 {
     if (logger.IsEnabled(LogLevel.Trace))
     {
         logger.LogTrace("accept msg<<<" + ByteBufferUtil.HexDump(msg));
     }
     jT808ReceiveAtomicCounterService.MsgSuccessIncrement();
 }
コード例 #2
0
        public void ByteBuffer_Hex16String_Convert_Test()
        {
            var hexString = ByteBufferUtil.ByteBufferToHex16(Encoding.UTF8.GetBytes("Hello"));
            var buffer    = ByteBufferUtil.Hex16ToByteBuffer(hexString);
            var value     = Encoding.UTF8.GetString(buffer);

            Assert.Equal("Hello", value);
        }
コード例 #3
0
        public void LongToBuffer_BufferToLong_Test()
        {
            var b1 = ByteBufferUtil.LongToBuffer(100L);
            var l1 = ByteBufferUtil.BufferToLong(b1);

            Assert.Equal(8, b1.Length);
            Assert.Equal(100L, l1);
        }
コード例 #4
0
        public Property LengthFrameEncoders_should_correctly_encode_anything_LittleEndian(
            Tuple <IByteBuf, ReadInstruction>[] reads)
        {
            var expectedReads = reads.Select(x => x.Item1).ToArray();
            var readModes     = reads.Select(x => x.Item2).ToArray();
            var partialReader = new PartialReadGenerator(readModes);
            var prepender     = new LengthFieldPrepender(4, false);
            var decoder       = new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4);
            var ec            = new EmbeddedChannel(partialReader, prepender, decoder);


            foreach (var read in expectedReads)
            {
                ec.WriteAndFlushAsync(read.Duplicate()).Wait();

                IByteBuf encoded;
                do
                {
                    encoded = ec.ReadOutbound <IByteBuf>();
                    if (encoded != null)
                    {
                        ec.WriteInbound(encoded);
                    }
                } while (encoded != null);
            }

            var actualReads = new List <IByteBuf>();

            // do one final read in case the last readmode was a partial
            ec.Pipeline.FireUserEventTriggered(PartialReadGenerator.FinishPartialReads.Instance);
            IByteBuf decoded;

            do
            {
                decoded = ec.ReadInbound <IByteBuf>();
                if (decoded != null)
                {
                    actualReads.Add(decoded);
                }
            } while (decoded != null);
            expectedReads = expectedReads.Select(x => x.ResetReaderIndex()).ToArray();
            // need to perform a read reset of the buffer
            var pass = expectedReads.SequenceEqual(actualReads, AbstractByteBuf.ByteBufComparer);

            if (!pass)
            {
                Debugger.Break();
            }

            return
                (pass
                 .When(reads.Length > 0    // need something to read
                       )
                 .Label($"Expected encoders and decoders to read each other's messages, even with partial reads. " +
                        $"Expected: {string.Join("|", expectedReads.Select(x => ByteBufferUtil.HexDump(x)))}" +
                        Environment.NewLine +
                        $"Actual: {string.Join("|", actualReads.Select(x => ByteBufferUtil.HexDump(x)))}"));
        }
コード例 #5
0
ファイル: TlsHandlerTest.cs プロジェクト: dora-BYR/Fenix
        public async Task TlsWrite(int[] frameLengths, bool isClient, SslProtocols serverProtocol, SslProtocols clientProtocol)
        {
            this.Output.WriteLine($"frameLengths: {string.Join(", ", frameLengths)}");
            this.Output.WriteLine($"isClient: {isClient}");
            this.Output.WriteLine($"serverProtocol: {serverProtocol}");
            this.Output.WriteLine($"clientProtocol: {clientProtocol}");

            var writeStrategy = new AsIsWriteStrategy();

            this.Output.WriteLine($"writeStrategy: {writeStrategy}");

            var executor = new SingleThreadEventExecutor("test executor", TimeSpan.FromMilliseconds(10));

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, serverProtocol, clientProtocol, writeTasks);

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (IEnumerable <int> lengths in frameLengths.Split(x => x < 0))
                {
                    ch.WriteOutbound(lengths.Select(len =>
                    {
                        var data = new byte[len];
                        random.NextBytes(data);
                        expectedBuffer.WriteBytes(data);
                        return((object)Unpooled.WrappedBuffer(data));
                    }).ToArray());
                }

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
                var         readBuffer      = new byte[16 * 1024 * 10];
                await ReadOutboundAsync(
                    async() =>
                {
                    int read = await driverStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                    return(Unpooled.WrappedBuffer(readBuffer, 0, read));
                },
                    expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

                bool isEqual = ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer);
                if (!isEqual)
                {
                    Assert.True(isEqual, $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");
                }
                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
コード例 #6
0
        public async Task TlsWrite(int[] frameLengths, bool isClient, SslProtocols protocol, string targetHost)
        {
            this.Output.WriteLine("frameLengths: " + string.Join(", ", frameLengths));
            this.Output.WriteLine($"protocol: {protocol}");
            this.Output.WriteLine($"targetHost: {targetHost}");

            var writeStrategy = new AsIsWriteStrategy();
            var executor      = new DefaultEventExecutor();

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, protocol, writeTasks, targetHost);

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (IEnumerable <int> lengths in frameLengths.Split(x => x < 0))
                {
                    ch.WriteOutbound(lengths.Select(len =>
                    {
                        var data = new byte[len];
                        random.NextBytes(data);
                        expectedBuffer.WriteBytes(data);
                        return((object)Unpooled.WrappedBuffer(data));
                    }).ToArray());
                }

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
                var         readBuffer      = new byte[16 * 1024 * 10];
                await ReadOutboundAsync(
                    async() =>
                {
                    int read = await driverStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                    return(Unpooled.WrappedBuffer(readBuffer, 0, read));
                },
                    expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

                Assert.True(ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer), $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");

                if (!isClient)
                {
                    // check if snihandler got replaced with tls handler
                    Assert.Null(ch.Pipeline.Get <SniHandler>());
                    Assert.NotNull(ch.Pipeline.Get <TlsHandler>());
                }

                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
コード例 #7
0
        public void Combine_Test()
        {
            var b1     = new byte[] { 1, 2 };
            var b2     = new byte[] { 3, 4 };
            var actual = ByteBufferUtil.Combine(b1, b2);

            Assert.Equal(4, actual.Length);
            Assert.Equal(new byte[] { 1, 2, 3, 4 }, actual);
        }
コード例 #8
0
 protected override void ChannelRead0(IChannelHandlerContext ctx, byte[] msg)
 {
     try
     {
         jT808SourcePackageDispatcher.SendAsync(msg);
         jT808UplinkPacket.ProcessorAsync(msg, JT808TransportProtocolType.tcp);
         //解析到头部,然后根据具体的消息Id通过队列去进行消费
         //要是一定要解析到数据体可以在JT808MsgIdHandlerBase类中根据具体的消息,
         //解析具体的消息体,具体调用JT808Serializer.Deserialize<T>
         JT808HeaderPackage jT808HeaderPackage = JT808Serializer.Deserialize <JT808HeaderPackage>(msg);
         jT808AtomicCounterService.MsgSuccessIncrement();
         jT808TrafficService.ReceiveSize(msg.Length);
         if (logger.IsEnabled(LogLevel.Trace))
         {
             logger.LogTrace("accept package success count<<<" + jT808AtomicCounterService.MsgSuccessCount.ToString());
             logger.LogTrace("accept msg <<< " + ByteBufferUtil.HexDump(msg));
         }
         jT808SessionManager.TryAdd(jT808HeaderPackage.Header.TerminalPhoneNo, ctx.Channel);
         if (handler.HandlerDict.TryGetValue(jT808HeaderPackage.Header.MsgId, out var handlerFunc))
         {
             IJT808Reply jT808Response = handlerFunc(new JT808Request(jT808HeaderPackage, msg));
             if (jT808Response != null)
             {
                 if (!jT808TransmitAddressFilterService.ContainsKey(ctx.Channel.RemoteAddress))
                 {
                     ctx.WriteAndFlushAsync(jT808Response);
                 }
             }
         }
         else
         {
             //未知的消息类型已日志形式输出
             if (unknownLogger.IsEnabled(LogLevel.Debug))
             {
                 unknownLogger.LogDebug(ByteBufferUtil.HexDump(msg));
             }
         }
     }
     catch (JT808.Protocol.Exceptions.JT808Exception ex)
     {
         jT808AtomicCounterService.MsgFailIncrement();
         if (logger.IsEnabled(LogLevel.Error))
         {
             logger.LogError("accept package fail count<<<" + jT808AtomicCounterService.MsgFailCount.ToString());
             logger.LogError(ex, "accept msg<<<" + ByteBufferUtil.HexDump(msg));
         }
     }
     catch (Exception ex)
     {
         jT808AtomicCounterService.MsgFailIncrement();
         if (logger.IsEnabled(LogLevel.Error))
         {
             logger.LogError("accept package fail count<<<" + jT808AtomicCounterService.MsgFailCount.ToString());
             logger.LogError(ex, "accept msg<<<" + ByteBufferUtil.HexDump(msg));
         }
     }
 }
コード例 #9
0
        protected override void Encode(IChannelHandlerContext context, string message, List <object> output)
        {
            if (message.Length == 0)
            {
                return;
            }

            output.Add(ByteBufferUtil.EncodeString(context.Allocator, message, encoding));
        }
コード例 #10
0
        /// <summary>
        /// Creates a buffer containing the error message from the given exception. If the cause is
        /// <c>null</c> returns an empty buffer.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="cause"></param>
        /// <returns></returns>
        public static IByteBuffer ToByteBuf(IChannelHandlerContext ctx, Exception cause)
        {
            if (cause is null || cause.Message is null)
            {
                return(Unpooled.Empty);
            }

            return(ByteBufferUtil.WriteUtf8(ctx.Allocator, cause.Message));
        }
コード例 #11
0
ファイル: StringEncoder.cs プロジェクト: wxlonstar/Fenix
        protected internal override void Encode(IChannelHandlerContext context, string message, List <object> output)
        {
            if (0u >= (uint)message.Length)
            {
                return;
            }

            output.Add(ByteBufferUtil.EncodeString(context.Allocator, message, this.encoding));
        }
コード例 #12
0
        /// <inheritdoc />
        protected internal override void EncodeInitialLine(IByteBuffer buf, IHttpRequest request)
        {
            ByteBufferUtil.Copy(request.Method.AsciiName, buf);

            string uri = request.Uri;

            if (string.IsNullOrEmpty(uri))
            {
                // Add / as absolute path if no is present.
                // See http://tools.ietf.org/html/rfc2616#section-5.1.2
                _ = buf.WriteMedium(SpaceSlashAndSpaceMedium);
            }
            else
            {
                var uriCharSequence = new StringBuilderCharSequence();
                uriCharSequence.Append(uri);

                bool needSlash = false;
                int  start     = uri.IndexOf("://", StringComparison.Ordinal);
                if (start != -1 && uri[0] != Slash)
                {
                    start += 3;
                    // Correctly handle query params.
                    // See https://github.com/netty/netty/issues/2732
                    int index = uri.IndexOf(QuestionMark, start);
                    if (index == -1)
                    {
                        if (uri.LastIndexOf(Slash) < start)
                        {
                            needSlash = true;
                        }
                    }
                    else
                    {
                        if (uri.LastIndexOf(Slash, index) < start)
                        {
                            uriCharSequence.Insert(index, Slash);
                        }
                    }
                }

                _ = buf.WriteByte(HorizontalSpace).WriteCharSequence(uriCharSequence, Encoding.UTF8);
                if (needSlash)
                {
                    // write "/ " after uri
                    _ = buf.WriteShort(SlashAndSpaceShort);
                }
                else
                {
                    _ = buf.WriteByte(HorizontalSpace);
                }
            }

            request.ProtocolVersion.Encode(buf);
            _ = buf.WriteShort(CrlfShort);
        }
コード例 #13
0
        static void WriteString(IByteBufferAllocator allocator, RedisMessageType type, string content, List <object> output)
        {
            IByteBuffer buf = allocator.Buffer(type.Length + ByteBufferUtil.Utf8MaxBytes(content) +
                                               RedisConstants.EndOfLineLength);

            type.WriteTo(buf);
            ByteBufferUtil.WriteUtf8(buf, content);
            buf.WriteShort(RedisConstants.EndOfLineShort);
            output.Add(buf);
        }
コード例 #14
0
        public static float GetFloat(byte[] src, int startIndex)
        {
            float result = BitConverter.ToSingle(src, startIndex);

            if (ByteBufferUtil.IsReveresed(_endian))
            {
                return(result.Reverse());
            }
            return(result);
        }
コード例 #15
0
        public static long GetLong(byte[] src, int startIndex)
        {
            long result = BitConverter.ToInt64(src, startIndex);

            if (ByteBufferUtil.IsReveresed(_endian))
            {
                return(result.Reverse());
            }
            return(result);
        }
コード例 #16
0
 public void OnHeadersRead(IChannelHandlerContext ctx, int streamId, IHttp2Headers headers, int padding, bool endOfStream)
 {
     if (endOfStream)
     {
         var content = ctx.Allocator.Buffer();
         content.WriteBytes(HelloWorldHttp1Handler.RESPONSE_BYTES.Duplicate());
         ByteBufferUtil.WriteAscii(content, " - via HTTP/2");
         this.SendResponse(ctx, streamId, content);
     }
 }
コード例 #17
0
        private static void EnsureWritableIntStatusShouldFailButNotThrow0(bool force)
        {
            var buf      = Unpooled.Buffer(1);
            var readOnly = buf.AsReadOnly();
            int result   = readOnly.EnsureWritable(1, force);

            Assert.Equal(1, result);
            Assert.False(ByteBufferUtil.EnsureWritableSuccess(result));
            readOnly.Release();
        }
コード例 #18
0
 protected override void Encode(IChannelHandlerContext context, string message, List <object> output)
 {
     if (message.Length == 0)
     {
         return;
     }
     // "#" +  length +  "packetid" + message + "!"
     message = "#" + (message.Length + 9).ToString().PadLeft(4, '0') + "999" + message + "!";
     output.Add(ByteBufferUtil.EncodeString(context.Allocator, message, Encoding.UTF8));
 }
コード例 #19
0
        public static short GetShort(byte[] src, int startIndex)
        {
            short result = BitConverter.ToInt16(src, startIndex);

            if (ByteBufferUtil.IsReveresed(_endian))
            {
                return(result.Reverse());
            }
            return(result);
        }
コード例 #20
0
        protected internal IByteBuffer Encode(IChannelHandlerContext context, IByteBuffer input)
        {
            var bytes = new byte[input.ReadableBytes];

            input.ReadBytes(bytes);

            var base64String = Convert.ToBase64String(bytes);

            return(ByteBufferUtil.EncodeString(context.Allocator, base64String, Encoding.ASCII));
        }
コード例 #21
0
 /**
  * If receive a frame with end-of-stream set, send a pre-canned response.
  */
 private static void OnHeadersRead(IChannelHandlerContext context, IHttp2HeadersFrame headers)
 {
     if (headers.IsEndStream)
     {
         var content = context.Allocator.Buffer();
         content.WriteBytes(Server.HelloWorldHttp1Handler.RESPONSE_BYTES.Duplicate());
         ByteBufferUtil.WriteAscii(content, " - via HTTP/2");
         SendResponse(context, content);
     }
 }
コード例 #22
0
        public string AsShortText()
        {
            string asShortText = this.shortValue;

            if (asShortText == null)
            {
                this.shortValue = asShortText = ByteBufferUtil.HexDump(this.data, MachineIdLen + ProcessIdLen + SequenceLen + TimestampLen, RandomLen);
            }

            return(asShortText);
        }
コード例 #23
0
        protected override void Encode(IChannelHandlerContext ctx, Person person, List <object> output)
        {
            if (person is null)
            {
                return;
            }

            var message = $"{person.Name}|{person.Age}" + Environment.NewLine;

            output.Add(ByteBufferUtil.EncodeString(ctx.Allocator, message, _encoding));
        }
コード例 #24
0
        public void DiscardReadBytes()
        {
            this.buffer.SetWriterIndex(0);
            for (int i = 0; i < this.buffer.Capacity; i += 4)
            {
                this.buffer.SetInt32(i, i, BitConverter.IsLittleEndian);
                this.buffer.SetWriterIndex(i + 4);
            }
            IArrayBuffer <byte> copy = Unpooled.CopiedBuffer(this.buffer);

            // Make sure there's no effect if called when readerIndex is 0.
            this.buffer.SetReaderIndex(Capacity / 4);
            this.buffer.MarkReaderIndex();
            this.buffer.SetWriterIndex(Capacity / 3);
            this.buffer.MarkWriterIndex();
            this.buffer.SetReaderIndex(0);
            this.buffer.SetWriterIndex(Capacity / 2);
            this.buffer.DiscardReadCount();

            Assert.Equal(0, this.buffer.ReaderIndex);
            Assert.Equal(Capacity / 2, this.buffer.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(copy.Slice(0, Capacity / 2), this.buffer.Slice(0, Capacity / 2)));
            this.buffer.ResetReaderIndex();
            Assert.Equal(Capacity / 4, this.buffer.ReaderIndex);
            this.buffer.ResetWriterIndex();
            Assert.Equal(Capacity / 3, this.buffer.WriterIndex);

            // Make sure bytes after writerIndex is not copied.
            this.buffer.SetReaderIndex(1);
            this.buffer.SetWriterIndex(Capacity / 2);
            this.buffer.DiscardReadCount();

            Assert.Equal(0, this.buffer.ReaderIndex);
            Assert.Equal(Capacity / 2 - 1, this.buffer.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(copy.Slice(1, Capacity / 2 - 1), this.buffer.Slice(0, Capacity / 2 - 1)));

            if (this.DiscardReadBytesDoesNotMoveWritableBytes())
            {
                // If writable bytes were copied, the test should fail to avoid unnecessary memory bandwidth consumption.
                Assert.False(ByteBufferUtil.Equals(copy.Slice(Capacity / 2, Capacity / 2), this.buffer.Slice(Capacity / 2 - 1, Capacity / 2)));
            }
            else
            {
                Assert.True(ByteBufferUtil.Equals(copy.Slice(Capacity / 2, Capacity / 2), this.buffer.Slice(Capacity / 2 - 1, Capacity / 2)));
            }

            // Marks also should be relocated.
            this.buffer.ResetReaderIndex();
            Assert.Equal(Capacity / 4 - 1, this.buffer.ReaderIndex);
            this.buffer.ResetWriterIndex();
            Assert.Equal(Capacity / 3 - 1, this.buffer.WriterIndex);

            copy.Release();
        }
コード例 #25
0
 static void WriteAscii(IByteBuffer buf, int offset, ICharSequence value)
 {
     if (value is AsciiString asciiString)
     {
         ByteBufferUtil.Copy(asciiString, 0, buf, offset, value.Count);
     }
     else
     {
         buf.SetCharSequence(offset, value, Encoding.ASCII);
     }
 }
コード例 #26
0
        private static void EncodePasswordAuthRequest(ISocks5PasswordAuthRequest message, IByteBuffer output)
        {
            output.WriteByte(0x01);

            output.WriteByte(message.Username.Length);
            output.WriteBytes(ByteBufferUtil.EncodeString(ByteBufferUtil.DefaultAllocator, message.Username,
                                                          Encoding.ASCII));

            output.WriteByte(message.Password.Length);
            output.WriteBytes(ByteBufferUtil.EncodeString(ByteBufferUtil.DefaultAllocator, message.Password,
                                                          Encoding.ASCII));
        }
コード例 #27
0
        public static void SetFloat(byte[] dst, ref int startIndex, float value)
        {
            byte[] src = BitConverter.GetBytes(value);

            if (ByteBufferUtil.IsReveresed(_endian))
            {
                Array.Reverse(src);
            }
            ByteBufferUtil.Copy(src, 0, dst, startIndex, src.Length);

            startIndex += sizeof(float);
        }
コード例 #28
0
        public void Compare2()
        {
            Assert.True(ByteBufferUtil.Compare(
                            WrappedBuffer(new[] { (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF }),
                            WrappedBuffer(new [] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00 }))
                        > 0);

            Assert.True(ByteBufferUtil.Compare(
                            WrappedBuffer(new [] { (byte)0xFF }),
                            WrappedBuffer(new [] { (byte)0x00 }))
                        > 0);
        }
コード例 #29
0
        public static FeatureCollection FromFlatGeobuf(byte[] bytes)
        {
            var fc = new NetTopologySuite.Features.FeatureCollection();

            var bb = new ByteBuffer(bytes);

            var headerSize = ByteBufferUtil.GetSizePrefix(bb);

            bb.Position = FlatBufferConstants.SizePrefixLength;
            var header = Header.GetRootAsHeader(bb);

            var count        = header.FeaturesCount;
            var nodeSize     = header.IndexNodeSize;
            var geometryType = header.GeometryType;
            var dimensions   = header.Dimensions;

            IList <ColumnMeta> columns = null;

            if (header.ColumnsLength > 0)
            {
                columns = new List <ColumnMeta>();
                for (int i = 0; i < header.ColumnsLength; i++)
                {
                    var column = header.Columns(i).Value;
                    columns.Add(new ColumnMeta()
                    {
                        Name = column.Name, Type = column.Type
                    });
                }
            }

            bb.Position += headerSize;

            if (nodeSize > 0)
            {
                var index     = new PackedHilbertRTree(count, nodeSize);
                var indexData = bytes.Skip(headerSize).Take((int)index.Size).ToArray();
                index.Load(indexData);
                bb.Position += (int)index.Size + (int)count * 8;
            }

            while (bb.Position < bb.Length)
            {
                var featureLength = ByteBufferUtil.GetSizePrefix(bb);
                bb.Position += FlatBufferConstants.SizePrefixLength;
                var feature = FeatureConversions.FromByteBuffer(bb, geometryType, dimensions, columns);
                fc.Add(feature);
                bb.Position += featureLength;
            }

            return(fc);
        }
コード例 #30
0
ファイル: Http2FrameLogger.cs プロジェクト: ywscr/SpanNetty
        private string ToString(IByteBuffer buf)
        {
            if (_level == InternalLogLevel.TRACE || buf.ReadableBytes <= BufferLengthThreshold)
            {
                // Log the entire buffer.
                return(ByteBufferUtil.HexDump(buf));
            }

            // Otherwise just log the first 64 bytes.
            int length = Math.Min(buf.ReadableBytes, BufferLengthThreshold);

            return(ByteBufferUtil.HexDump(buf, buf.ReaderIndex, length) + "...");
        }