Netty的各种编解码器

今天我学习了Netty的各种编解码器,包括基于长度域的编解码器、基于分隔符的编解码器等,掌握了Netty的粘包和拆包处理技术。下面是一个使用长度域编解码器的服务器:

public class Server {

 

    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup workerGroup = new NioEventLoopGroup();

 

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup)

                    .channel(NioServerSocketChannel.class)

                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override

                        protected void initChannel(SocketChannel ch)

                                throws Exception {

                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2), new LengthFieldPrepender(2), new ServerHandler());

                        }

                    });

 

            ChannelFuture future = bootstrap.bind(8080).sync();

            future.channel().closeFuture().sync();

        } finally {

            bossGroup.shutdownGracefully();

            workerGroup.shutdownGracefully();

        }

    }

}

posted @ 2023-05-22 21:19  ITJAMESKING  阅读(67)  评论(0编辑  收藏  举报