LengthFieldBasedFrameDecoder
的用法。
构造方法
1 2 3
| public LengthFieldBasedFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) { this(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, true); }
|
lengthFieldOffset
lengthFieldLength
lengthAdjustment
initialBytesToStrip
1 2 3 4 5 6 7 8 9 10
| * lengthFieldOffset = 1 (= the length of HDR1) * lengthFieldLength = 2 * <b>lengthAdjustment</b> = <b>1</b> (= the length of HDR2) * <b>initialBytesToStrip</b> = <b>3</b> (= the length of HDR1 + LEN) * * BEFORE DECODE (16 bytes) AFTER DECODE (13 bytes) * +------+--------+------+----------------+ +------+----------------+ * | HDR1 | Length | HDR2 | Actual Content |----->| HDR2 | Actual Content | * | 0xCA | 0x000C | 0xFE | "HELLO, WORLD" | | 0xFE | "HELLO, WORLD" | * +------+--------+------+----------------+ +------+----------------+
|
lengthFieldOffset
对应 0xCA
lengthFieldLength = 2
,表示有 2
个字节表示长度,对应 0x000C
,十进制表示 12,而 HELLO, WORLD
正好是 12 字节
lengthAdjustment
表示还有多少个字节才是正式内容,参数是 1
个字节,对应 0xFE
initialBytesToStrip
表示去掉多少个字节,向下传递
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package com.chat.protocol;
import com.chat.message.LoginRequestMessage; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LoggingHandler;
public class TestMessageCode {
public static void main(String[] args) throws Exception {
EmbeddedChannel embeddedChannel = new EmbeddedChannel( new LengthFieldBasedFrameDecoder(1024,0,4,0,0), new LoggingHandler() );
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); byte[] bytes = "hello world".getBytes(); int length = bytes.length; byteBuf.writeInt(length); byteBuf.writeBytes(bytes); embeddedChannel.writeInbound(byteBuf);
}
}
|
输出
1 2 3 4 5 6 7
| 14:40:58.255 [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 15B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 00 00 00 0b 68 65 6c 6c 6f 20 77 6f 72 6c 64 |....hello world | +--------+-------------------------------------------------+----------------+ 14:40:58.256 [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ COMPLETE
|