1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| ServerBootstrap和Bootstrap启动类
EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap.group(bossGroup, workerGroup); 放入两个group,一个acceptor线程池,一个io的work线程池,不填默认为Runtime.getRuntime().availableProcessors() * 2个线程 NioEventLoopGroup由EventExcutor数组构成,通过newChild构建NioEventLoop数组 NioEventLoop内部有selector
bootstrap.channel(NioServerSocketChannel.class); 内部构建一个channelFactory为:channelFactory(new ReflectiveChannelFactory<C>(channelClass)); 后期直接ChannelFactory#newChannel来实例化Channel 每次实例化一个NioSocketChannel等类型都会自带一个pipeline = newChannelPipeline(); 并且这个ChannelPipeline还自带head和tail两个ChannelHandlerContext
服务器版 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { pipeline.addLast(......); } }); 直接给ServerBootStrap相关的childHandler
ServerBootStrap#bind--->doBind--->initAndRegister 首先实例一个新的channel:channelFactory.newChannel(); ---->ServerBootstrap#init 1:channel.config().setOptions(options); 2:ChannelPipeline p = channel.pipeline(); 3:p.addLast(new ChannelInitializer<Channel>() { pipeline.addLast( new ServerBootstrapAcceptor(currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs) ); }) 添加一个ServerBootstrapAcceptor,等待ChannelInitializer#channelRegistered----->initChannel 将相关的ServerBootstrapAcceptor绑定带主handler后马上进行ctx.pipeline().fireChannelRegistered();
这样ServerBootStrapAcceptor会激活channelRead进行以下几步 1:channel.pipeline().addLast(childHandler);
2:childGroup.register(child)
最后ServerBootStrap#doBind0
bossGroup的启动起来 channel.eventLoop().execute(new Runnable() { @Override public void run() { if (regFuture.isSuccess()) { channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } else { promise.setFailure(regFuture.cause()); } } });
客户端版本 BootStrap#connect---->doResolveAndConnect---->initAndRegister
channelFactory.newChannel(); 得到channel一个channel
config().group().register(channel); 从线程池拿出一个线程selector绑定channel
并在ChannelInitializer添加handler
BootStrap##doConnect
channel.eventLoop().execute(new Runnable() { @Override public void run() { if (localAddress == null) { channel.connect(remoteAddress, connectPromise); } else { channel.connect(remoteAddress, localAddress, connectPromise); } connectPromise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } });
绑定相关channel的eventloop线程启动
|
国内查看评论需要代理~