1. 程式人生 > >Netty4實戰第十六章:登出/註冊EventLoop

Netty4實戰第十六章:登出/註冊EventLoop

        //建立兩個EventLoopGroup例項
        EventLoopGroup group = new NioEventLoopGroup();
        final EventLoopGroup group2 = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .handler(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
                        ctx.pipeline().remove(this);
                        //登出掉
                        ChannelFuture cf = ctx.deregister();
                        cf.addListener((ChannelFutureListener) future -> {
                            //登出成功後註冊到另一個EventLoopGroup
                            group2.register(future.channel());
                        });
                    }
                });
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("www.manning.com", 80));
        future.addListener((ChannelFutureListener) channelFuture -> {
            if (channelFuture.isSuccess()) {
                System.out.println("Connection established");
            } else {
                System.err.println("Connection attempt failed");
                channelFuture.cause().printStackTrace();
            }
        });
  可以看到修改Channel的EventLoop也是很簡單的。最需要注意的地方就是deregister(…)和register(…)方法是非同步的,要通過檢查ChannelFuture或新增ChannelFutureListener來確定你的註冊或登出操作已經完成。如果不檢查可能就會出現重複註冊的情況,重複註冊就會觸發IllegalStateException異常。