netty笔记1

EventLoopGroup.next()得到EventLoop
EventLoopGroup初始化时候会实例化一个EventLoop[]数组,使用的是EventLoopGroup的newChild方法


真正干活的是EventLoop
使用EventLoopGroup的register方法会将channel注册到一个EventLoop上
在AbstractBootstrap的initAndRegister方法中会做这一步操作


ServerBootstrap的init方法会将server端接收到的channel的pipeline加上配置的ChannelHandler
Bootstrap的init方法会将client端接的channel的pipeline加上配置的ChannelHandler




DefaultChannelPipeline在addLast后会判断当前的channel是否注册到EventLoop上,如果没有会用一个task
在注册后调用ChannelHandler的handlerAdded方法


ChannelInitializer的handlerAdded方法会先执行initChannel,最后执行remove方法将当前的ChannelInitializer移除pipeline

ServerBootstrap中
 p.addLast(new ChannelInitializer<Channel>() { //p是serverChannel的pipeline
            @Override
            public void initChannel(final Channel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline(); //ch是serverChannel
                ChannelHandler handler = config.handler();//handler得到AbstractBootstrap的handler,也就是handler(handler)设置的
                if (handler != null) {
                    pipeline.addLast(handler);
                }

                ch.eventLoop().execute(new Runnable() {
                    @Override
                    public void run() {
                        pipeline.addLast(new ServerBootstrapAcceptor(//serverChannel的pipeline加上ServerBootstrapAcceptor
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });

ServerBootstrapAcceptor中的channelRead会在serverChannel.accept得到channel后执行,加上childHandler,使用childGroup注册一个EventLoop


NioEventLoop有一个run方法,做了processSelectedKeys和runAllTasks,
这个run方法会最先执行    SingleThreadEventExecutor.execute方法中startThread()会将run方法包装成一个task执行


processSelectedKeys会选择注册在selector上的事件,然后AbstractNioChannel.NioUnsafe处理
比如read 先调用doReadMessages读取内容,然后使用pipeline处理,AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext, Object)
生成一个任务提交给channel的EventLoop处理


EventLoopGroup和EventLoop的executor默认是executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());  

直接生成新的FastThreadLocalThread执行

AbstractChannel
   AbstractNioChannel
      AbstractNioByteChannel       ----NioByteUnsafe
     NioSocketChannel
 AbstractNioMessageChannel    ----NioMessageUnsafe
     NioServerSocketChannel

猜你喜欢

转载自blog.csdn.net/u013038630/article/details/77869658
今日推荐