使用版本4.1.12.Final。边学习,边总结。如侵权,请报删。
因为也是初学,错误地方请指正并见谅
ServerBootstrap初始化
- ServerBootstrap初始化
io.netty.bootstrap包中的ServerBootstrap方法中有初始化ServerBootstrap的一些方法
以最简单的EchoServer.class为例(代码不写全)
- ServerBootstrap初始化
ServerBootstrap b = new ServerBootstrap();
b.group(group)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
//覆盖initChannel方法
});
分别调用ServerBootstrap中的方法对ServerBootstrap对象b进行初始化。
我觉得过程稍微有点像Build设计模式。
调用这几个方法 给对象中的以下字段赋值:
private volatile EventLoopGroup childGroup;
ChannelFactory<C extends Channel> channelFactory;//AbstractBootstrap
private volatile SocketAddress localAddress;
private volatile ChannelHandler childHandler;//AbstractBootstrap
volatile 关键字可以使数据在多线程中可见和防止指令重排序,但不能保证原子性。适合单个线程写入,多个线程读取。
调用channel方法是进入下面的方法 (AbstractBootstrap.class类中的方法),
AbstractBootstrap.class(抽象类)是ServerBootstrap.class的父类
@Deprecated
public B channelFactory(ChannelFactory<? extends C> channelFactory) {
if (channelFactory == null) {
throw new NullPointerException("channelFactory");
}
if (this.channelFactory != null) {
throw new IllegalStateException("channelFactory set already");
}
this.channelFactory = channelFactory;
return this;
}