Netty的Channel Handler和编解码器

今天我学习了NettyChannel Handler和编解码器,掌握了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 MyDecoder(), new MyEncoder(), new ServerHandler());

                        }

                    });

 

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

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

        } finally {

            bossGroup.shutdownGracefully();

            workerGroup.shutdownGracefully();

        }

    }

}

 

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