Netty基礎チュートリアル-4、helloworld(最適化版)

22031 ワード

機能実装
サービス側
  • クライアントデータ
  • を受け取る.
  • 応答結果はクライアント
  • に与える.
    クライアント
  • は、要求をサービス側
  • に送信する.
  • サービス側の応答を受け入れる
  • サービス側実装
    起動クラス:Server.java
    public class Server {
        public static void main(String[] args) throws Exception{
            //     ,                    
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workGroup = new NioEventLoopGroup();
            ServerBootstrap b = new ServerBootstrap();
            //     
            ChannelFuture cf = b.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                    //1)
                    .childHandler(new ServerChannelInit())
                    .bind(8899)
                    .sync();
            System.out.println("        !!!");
            //         
            cf.channel().closeFuture().sync();
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            System.out.println("       !!!");
        }
    }
    

    1)、ここで業ロジックを注入して、これでよく業務とIO操作を分離した
    チャネル初期化クラス:ServerChannelInit.java
    public class ServerChannelInit extends ChannelInitializer<NioSocketChannel> {
        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            //          ,   ,Handler       
            ch.pipeline()
                    .addLast(new StringEncoder())
                    .addLast(new StringDecoder())
                    .addLast(new ServerHandler());
        }
    }
    

    チャネルデータ処理クラス:ServerHandler.java
    public class ServerHandler extends SimpleChannelInboundHandler<String> {
    
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                System.out.println("      :"+msg);
                //    
                ctx.writeAndFlush("         !!");
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("=============test    ============");
            super.channelActive(ctx);
        }
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("=============test    ing============");
            super.channelInactive(ctx);
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            System.out.println("=============test        !!============");
            super.channelReadComplete(ctx);
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("=============test        ============");
            super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    }
    

    クライアント実装
    起動クラス:Client.java
    public class Client {
        public static void main(String[] args) throws Exception{
            NioEventLoopGroup workGroup = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            ChannelFuture cf = b.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientChannelInit())
                    .connect("127.0.0.1", 8899)
                    .sync();
            server",CharsetUtil.UTF_8));
            System.out.println("        !!!!");
            cf.channel().closeFuture().sync();
        }
    }
    

    チャネル初期化クラス:ClientChannelInit.java
    public class ClientChannelInit extends ChannelInitializer<NioSocketChannel> {
        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(new StringEncoder())
                    .addLast(new StringDecoder())
                    .addLast(new ClientHandler());
        }
    }
    

    チャネルデータ処理クラス:ClientHandler.java
    public class ClientHandler extends SimpleChannelInboundHandler<String> {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                System.out.println("         :"+msg);
        }
    
        /**
         *  channel      ,    
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush("hello server");
        }
    }
    

    まとめ
    1、ここではSimpleChannelInboundHandler(nettyが提供するクラス)を使用しています.これにより、データの操作がより簡単になります.伝達される汎用型はデータのタイプであり、リソースの問題を管理してくれます.
    2、StringDecoderとStringEncoderクラスを使用して、下位レベルでデータの変換を処理してくれて、handlerのビジネスロジックにもっと集中することができます.githubソース:https://github.com/wcjwctwy/netty-study