参见 Netty的 LengthFieldBasedFrameDecoder

    1. public class TestLengthDecoder {
    2. public static void main(String[] args) {
    3. EmbeddedChannel channel = new EmbeddedChannel(
    4. new LengthFieldBasedFrameDecoder(1024,0,4,0,4),
    5. new LoggingHandler(LogLevel.DEBUG),
    6. new ChannelInboundHandlerAdapter(){
    7. @Override
    8. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    9. ByteBuf buf = (ByteBuf) msg;
    10. System.out.println(buf.toString(Charset.defaultCharset()));
    11. }
    12. }
    13. );
    14. ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
    15. buf.writeInt(12);
    16. buf.writeBytes("hello, world".getBytes());
    17. buf.writeInt(6);
    18. buf.writeBytes("你好".getBytes());
    19. channel.writeInbound(buf);
    20. }
    21. }