netty的启动过程是咋样的,就是那里启动了socket监听,咋处理请求的( 五 )


public static ChannelFuture bind(Channel channel, SocketAddress localAddress) { if (localAddress == null) { throw new NullPointerException("localAddress"); } ChannelFuture future = future(channel); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.BOUND, localAddress)); return future; }在Channels.bind方法中我们又看到了
channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.BOUND, localAddress)); 【netty的启动过程是咋样的,就是那里启动了socket监听,咋处理请求的】 通过channel获取到pipeline,然后封装了一个DownstreamChannelStateEvent事件,发给下行请求。 继续跟踪下去,我们看到了 DownstreamChannelStateEvent BOUND事件来到了NioServerSocketPipelineSink.handleServerSocket(ChannelEvent e)
private static void handleServerSocket(ChannelEvent e) { if (!(e instanceof ChannelStateEvent)) { return; } ChannelStateEvent event = (ChannelStateEvent) e; NioServerSocketChannel channel = (NioServerSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = https://www.zhihu.com/api/v4/questions/38969301/event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { ((NioServerBoss) channel.boss).close(channel, future); } break; case BOUND: if (value != null) { ((NioServerBoss) channel.boss).bind(channel, future, (SocketAddress) value); } else { ((NioServerBoss) channel.boss).close(channel, future); } break; default: break; } }``` java ((NioServerBoss) channel.boss).bind(channel, future, (SocketAddress) value);里面的bind方法如下:void bind(final NioServerSocketChannel channel, final ChannelFuture future, final SocketAddress localAddress) { registerTask(new RegisterTask(channel, future, localAddress));}接下来我们看RegisterTask:``` java private final class RegisterTask implements Runnable { private final NioServerSocketChannel channel; private final ChannelFuture future; private final SocketAddress localAddress; public RegisterTask(final NioServerSocketChannel channel, final ChannelFuture future, final SocketAddress localAddress) { this.channel = channel; this.future = future; this.localAddress = localAddress; } public void run() { boolean bound = false; boolean registered = false; try { channel.socket.socket().bind(localAddress, channel.getConfig().getBacklog()); bound = true; future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); channel.socket.register(selector, SelectionKey.OP_ACCEPT, channel); registered = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (!registered \u0026amp;\u0026amp; bound) { close(channel, future); } } } }}


推荐阅读