LengthFieldBasedFrameDecoder使用

LengthFieldBasedFrameDecoder解碼器,會讀取byteBuf中的前幾個字節,獲取數據長度。

作用是防止粘包。

如果客戶端也是netty,那麼可以配合LengthFieldPrepender使用。LengthFieldPrepender會自動在原始數據前面加上數據長度。

socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535,0,2,0,2));

第二個參數指定lengthFieldOffset,也就是長度字段的偏移距,一般設置爲0
第三個參數指定lengthFieldLength,也就是幾個字節,2個字節的話,一個frame最多65535個字節,short類型的最大值。
lengthAdjustment, initialBytesToStrip,後面2個參數,lengthAdjustment一般爲0,initialBytesToStrip和lengthFieldLength保持一致。

使用示例
服務端

public class EchoServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
//                            ByteBuf delimiter0 = Unpooled.copiedBuffer("A".getBytes());
//                            ByteBuf delimiter1 = Unpooled.copiedBuffer("B".getBytes());

//                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter,delimiter0,delimiter1));
//                            socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(10));

//                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                            socketChannel.pipeline().addLast(new MsgpackDecoder());
                            socketChannel.pipeline().addLast(new LengthFieldPrepender(2));
                            socketChannel.pipeline().addLast(new MsgpackEncoder());

                            socketChannel.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture channelFuture =serverBootstrap.bind(7799).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class EchoServerHandler extends SimpleChannelInboundHandler<Object> {


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        System.out.println(o);
//        o +="$_";
//        ByteBuf echo = Unpooled.copiedBuffer(o.getBytes());
        channelHandlerContext.writeAndFlush(o);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

客戶端

public class EchoClient {
    public void connect(int port,String host){
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
//                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
//                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                            socketChannel.pipeline().addLast(new MsgpackDecoder());
                            socketChannel.pipeline().addLast(new LengthFieldPrepender(2));
                            socketChannel.pipeline().addLast(new MsgpackEncoder());

                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture channelFuture=b.connect(host,port).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        EchoClient echoClient = new EchoClient();
        echoClient.connect(7799,"127.0.0.1");
    }
}
public class EchoClientHandler extends SimpleChannelInboundHandler<Object> {
    public static  final String STRINGTAG="HELLO,這是什";
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        List<UserInfo> userInfos = new ArrayList<>();
        for (int i =0;i<2;i++){
            UserInfo userInfo = new UserInfo();
            userInfo.setName("張三"+i);
            userInfo.setAge(i);
            userInfos.add(userInfo);
            ctx.write(userInfo);

        }
        ctx.flush();
//        ctx.writeAndFlush(userInfos);
//        for (int i=0;i<10;i++){
//            ctx.writeAndFlush(Unpooled.copiedBuffer(STRINGTAG.getBytes()));
//            Thread.sleep(3000);
//            ctx.writeAndFlush(Unpooled.copiedBuffer("麼你A好嗎$_不是B".getBytes()));
//            ctx.writeAndFlush(Unpooled.copiedBuffer(new byte[1024]));
//        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        System.out.println(o);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章