Netty学习(四)—LengthFieldBasedFrameDecoder解码器
LengthFieldBasedFrameDecoder和LengthFieldPrepender组合是解决TCP粘包和拆包问题的最佳方案,通过将消息分为消息头和消息体记录消息长度解决读半包问题;
个人主页:tuzhenyu’s page
原文地址:Netty学习(四)—LengthFieldBasedFrameDecoder解码器
(0)使用实例
- 在发送端添加LengthFiledPrepender编码器,为发送的消息添加表示消息长度的消息头
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast("encoder", new LengthFieldPrepender(4,false));
socketChannel.pipeline().addLast(new ClientHandler());
}
});
public void channelActive(ChannelHandlerContext ctx) throws Exception {
byte[] req = null;
ByteBuf buffer = null;
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("abcdefghijklmnopqrstuvwxyz");
}
req = sb.toString().getBytes();
buffer = Unpooled.buffer(req.length);
buffer.writeBytes(req);
ctx.writeAndFlush(buffer);
}
- 在接收端添加LengthFieldBasedFrameDecoder解码器,根据消息头中消息总长度接收消息并去除消息头往下传递消息体数据;
ServerBootstrap b= new ServerBootstrap();
b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,1024)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()