Netty 组件Channel

服务端Channel的创建

在服务端需要绑定端口,下面通过源码来进行分析
ChannelFuture future = server.bind(8888).sync();
bind()方法入口,到AbstractBootstrap#doBind

private ChannelFuture doBind(final SocketAddress localAddress) {
   // 初始化channel并注册到EventLoopGroup中
    final ChannelFuture regFuture = initAndRegister();  
    final Channel channel = regFuture.channel();  
    if (regFuture.cause() != null) {  
        return regFuture;  
    }   
    // 省略...
}

进入initAndRegister方法

final ChannelFuture initAndRegister() {  
    Channel channel = null;  
 try {  
        // 创建Channel
        channel = channelFactory.newChannel();
        //初始化Channel
        init(channel);
    }
    // 省略...

查看channelFactory.newChannel()方法,进入的是ReflectiveChannelFactory#newChannel方法。

public T newChannel() {  
    try {  
        return clazz.newInstance();  
  } catch (Throwable t) {  
        throw new ChannelException("Unable to create Channel from class " + clazz, t);  
  }  
}

到此,可以知道是通过Java反射生成的Channel对象,那么这里的clazz是哪个类呢?
查看ReflectiveChannelFactory构造方法

public ReflectiveChannelFactory(Class<? extends T> clazz) {  
    if (clazz == null) {  
        throw new NullPointerException("clazz");  
  }  
    this.clazz = clazz; 
}

ServerBootstrap设置参数,继续看的之前实例的代码

server.group(masterGroup, workerGroup)  
        .channel(NioServerSocketChannel.class)  
        .handler(new Serverhandler()) // 接受客户端连接信息  
  .childHandler(new ChannelInitializer<Channel>() {  
            @Override  
  protected void initChannel(Channel ch) throws Exception {  
                 // 业务逻辑  
  System.out.println("business logic");  
  }  
        });

查看channel()方法

public B channel(Class<? extends C> channelClass) {  
    if (channelClass == null) {  
        throw new NullPointerException("channelClass");  
  }  
    return channelFactory(new ReflectiveChannelFactory<C>(channelClass)); //这里传递参数
}

服务端Channel的初始化

  • ServerBootstrap#init初始化入口
  • set ChannelOptions, ChannelAttrs
  • set ChildOptions, ChildAttrs
  • 添加Handler到Pipeline
  • 最后在Pipeline添加ServerBootstrapAcceptor
添加新评论