1.服务器就是在这个bind()里启动完成的
2.Bind()代码,追踪到创建了一个端口对象,并做了一些空判断,核心代码 doBind
public ChannelFuture bind(SocketAddress localAddress){
validate();
if(localAddress=null){
throw new NullPointerException("localAddress");
return doBind(localAddress);
}
3.doBind源码里,核心是两个方法 initAndRegister() 和 doBind0()
private ChannelFuture doBind(final SocketAddress localAddress){
final ChannelFuture regFuture=initAndRegister();
final Channel channel=regFuture.channel();
if (regFuture.cause()!=null){
return regFuture;
}
if(regFuture.isDone()){
// At this point we know that the registration was complete and successful
ChannelPromise promise = channel.newPromise();
//===============================
//说明:执行 doBind方法,完成对端口的绑定
//===============================
doBind0(regFuture,channel,localAddress,promise);
retum promise;
}else{
//Registration future is almost alwaysfulfilled already,but just in case it's not.
final PendingRegistrationPromise promise=new PendingRegistrationPromise(channel);
regFuture.addListener(new ChannelFutureListener(){
@Override
public void operationComplete(ChannelFuture future)throws Exception{
Throwable cause-future.cause();
if(cause!=null){
//Registration on the EventLoop failed sofail the ChannelPromise directly to not cause an
// IllegalStateException once we try toaccess the EventLoop of the Channel.
promise.setFailure(cause);
}else{
//Registration was successful,so set the correct executor to use.
//See https://github.com/netty/netty/issues/2586
promise.registered();
doBind0(regFuture,channel,localAddress,promise);
}
}
});
return promise;
}
}