public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyServerHandler());
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
}
}
1.LengthFieldBasedFrameDecoder
new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4)
LengthFieldBasedFrameDecoder.png
lengthFieldOffset
虽然是字段上翻译为偏移量,其实可以理解为一个HeaderlengthFieldLength
意思是真实内容的字节长度lengthAdjustment
可以理解为第二个HeaderinitialBytesToStrip
意思是从字节流开始,跳过多少个字节解释一下:
lengthFieldOffset,lengthAdjustment是0,所以没有header,只有真实字节长度加上真实内容,又因为跳过0个字节,所以读取这个字节流的所有内容。
image.png
image.png
image.png image.png
2.StringDecoder
将字节码转换为字符串
3.new LengthFieldPrepender(4)
image.png4.new StringEncoder(CharsetUtil.UTF_8)
转换为字节码
网友评论