nettyのdemo

6271 ワード

1.サーバ側の作成:
public class ServerMain {
    public static void run() {
        EventLoopGroup pGroup = new NioEventLoopGroup(); //   :          (       )
        EventLoopGroup cGroup = new NioEventLoopGroup(); //   :          
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(pGroup, cGroup)
                    //     channel
                    .channel(NioServerSocketChannel.class) 
                    //    ,              
                    // .option(ChannelOption.SO_BACKLOG, 1024)
                    //   ,        
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    //        .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer() {
                        protected void initChannel(SocketChannel sc) throws Exception {
                            sc.pipeline()
                                    //    ByteBuf    
                                    .addLast(new StringDecoder())
                                    //      ,          String  
                                    //.addLast(new StringEncoder())
                                    .addLast(new ServerHandlerOne());   //        
                        }
                    });
            ChannelFuture cf = null;
            cf = b.bind(8080).sync();
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            pGroup.shutdownGracefully();
            cGroup.shutdownGracefully();
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new Thread(
                () -> {
                    run();
                }
        ).start();

    }
}

サービス側処理クラス:
public class ServerHandlerOne extends SimpleChannelInboundHandler {

    private static int count = 0;
    
    //SimpleChannelInboundHandler         
    protected void channelRead0(ChannelHandlerContext ctx, String o) throws Exception {
        //    
        String[] split = o.split("&");
        Arrays.stream(split).forEach((a) -> {
            System.out.println(a);
        });
        //          ByteBuf   .
        ReferenceCountUtil.release(o);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("     " + count++);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("         " + count++);
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("           ");
        super.channelActive(ctx);
        ByteBuf b = Unpooled.copiedBuffer("     ".getBytes());
        ctx.writeAndFlush(b);
    }
}

 
2.クライアント;
public class ClientMain {

    public static void run() {
        EventLoopGroup cGroup = new NioEventLoopGroup(); //   :          
        try {
            Bootstrap b = new Bootstrap();
            b.group(cGroup)
                    .channel(NioSocketChannel.class) //     channel
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    // .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer() {
                        protected void initChannel(SocketChannel sc) throws Exception {
                            //5s    ,    channel
                            sc.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new ClientHandler())
                                    .addLast(new ClientHandler2());
                        }
                    });
            ChannelFuture localhost = b.connect("localhost", 8080);
            // localhost.addListener(ChannelFutureListener.CLOSE);
            localhost.channel().closeFuture().sync();
            System.out.println("aaaa");
        } catch (Exception e) {
            cGroup.shutdownGracefully();
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        run();
    }
}

2つのクライアント処理クラス:
public class ClientHandler extends SimpleChannelInboundHandler {

    protected void channelRead0(ChannelHandlerContext ctx, String) throws Exception {
        System.out.println(o);
        //                       
        ctx.fireChannelRead(o);
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(1);
        //                       
        ctx.fireChannelActive();
        new Thread(() -> {
            String s = "   &";
            int i = 0;
            do {
                ByteBuf b = Unpooled.buffer(s.length());
                try {
                    b.writeBytes(s.getBytes("utf-8"));
                   //       ,          
                   // Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ctx.writeAndFlush(b);
                i++;
            } while (i != 10);
        }).start();
    }

}
public class ClientHandler2 extends SimpleChannelInboundHandler {

    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        System.out.println(o.toString() + 2);
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(2);

    }
}

 
注意:短い接続では、クライアントが情報を送信するたびに、サーバの応答を得た後、パイプリソースを閉じることができます.長い接続は心拍メカニズムで接続状況を検出することができる.