上一篇【第25篇】Netty优雅关闭——让系统体面地说再见
下一篇【第27篇】Netty OP_ACCEPT事件处理源码解析——新连接是怎么被接入的
开篇故事
某大厂面试现场:
面试官:“ServerBootstrap.bind(8080)后面到底发生了什么?”
候选人:“呃…就是绑定端口…”
面试官:“那NioServerSocketChannel是什么时候创建的?注册到Selector又是什么时候?”
候选人:“这个…不太清楚…”
面试官内心:“又是一个只会用不会看源码的…”
一、启动流程总览
Netty服务端启动的完整链路:
ServerBootstrap.bind(port)
→ doBind(localAddress)
→ initAndRegister() ← 创建Channel + 初始化 + 注册
→ channelFactory.newChannel() ← 反射创建NioServerSocketChannel
→ init(channel) ← 设置Options、添加ServerBootstrapAcceptor
→ group().register(channel) ← 注册到Selector
→ doBind0() ← 绑定端口
→ channel.bind(localAddress, promise)
→ pipeline.bind(localAddress, promise)
→ HeadContext.bind()
→ unsafe.bind()
→ doBind(localAddress) ← JDK NIO bind
→ pipeline.fireChannelActive()
→ doBeginRead() ← 设置OP_ACCEPT
二、核心源码:initAndRegister()
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
channel = channelFactory.newChannel(); // 1. 反射创建NioServerSocketChannel
init(channel); // 2. 初始化
} catch (Throwable t) {
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
ChannelFuture regFuture = config().group().register(channel); // 3. 注册
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
return regFuture;
}
init()方法是服务端特有的:
void init(Channel channel) {
setChannelOptions(channel, options);
setAttributes(channel, attrs);
ChannelPipeline p = channel.pipeline();
// 关键!添加ServerBootstrapAcceptor处理新连接
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(final Channel ch) {
ch.pipeline().addLast(new ServerBootstrapAcceptor(ch, currentChildGroup,
currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
ServerBootstrapAcceptor是核心:
private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) {
final Channel child = (Channel) msg;
child.pipeline().addLast(childHandler); // 添加用户配置的childHandler
childGroup.register(child).addListener(f -> { // 注册到workerGroup
if (!f.isSuccess()) child.unsafe().closeForcibly();
});
}
}
三、完整时序图
时间轴 →
T1: ServerBootstrap.bind(8080)
T2: → channelFactory.newChannel()
→ new NioServerSocketChannel() ← JDK ServerSocketChannel创建
→ super(null) → newSocket(SelectorProvider) → ServerSocketChannel.open()
T3: → init(channel)
→ channel.pipeline().addLast(ServerBootstrapAcceptor)
T4: → group().register(channel) → next().register(channel)
→ eventLoop.execute(() → register0(promise))
T5: → doRegister() → javaChannel().register(selector, 0, this)
T6: → pipeline.fireChannelRegistered()
T7: → pipeline.fireChannelActive() // 此时还不活跃,不计
T8: → doBind0()
→ channel.bind(localAddress)
T9: → doBind() → javaChannel().socket().bind(address, backlog)
T10: → pipeline.fireChannelActive()
→ doBeginRead() → selectionKey.interestOps(OP_ACCEPT)
T11: ✅ 启动完成,开始监听OP_ACCEPT事件
四、实战:验证启动流程
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class BootstrapDebugServer {
public static void main(String[] args) throws Exception {
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
System.out.println(">>> Boss Channel 已注册: " + ctx.channel());
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println(">>> Boss Channel 已激活,开始监听OP_ACCEPT");
}
})
.childHandler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
System.out.println(">>> Child Channel 已注册: " + ctx.channel());
}
});
ChannelFuture f = b.bind(8080).sync();
System.out.println("端口绑定完成!");
f.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
输出:
>>> Boss Channel 已注册: [id: 0x...]
>>> Boss Channel 已激活,开始监听OP_ACCEPT
端口绑定完成!
五、总结
| 步骤 | 核心类 | 操作 |
|---|---|---|
| 创建Channel | channelFactory | 反射创建NioServerSocketChannel |
| 初始化 | ServerBootstrap.init() | 添加ServerBootstrapAcceptor |
| 注册 | AbstractUnsafe.register() | 注册到Selector |
| 绑定 | doBind() | 调用JDK bind() |
| 激活 | doBeginRead() | 设置OP_ACCEPT |
上一篇【第25篇】Netty优雅关闭——让系统体面地说再见
下一篇【第27篇】Netty OP_ACCEPT事件处理源码解析——新连接是怎么被接入的
1145


—— 服务端启动全剖析&spm=1001.2101.3001.11974&articleId=162114962&d=1&t=3&u=d8eee634aed74b8282d58ed8d689ba15)

被折叠的 条评论
为什么被折叠?



