在了解NioServerSocketChannel之前 了解个nio selector多路复用的例子
public class NioSelectorServer {
public static void main(String[] args) throws Exception{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9002));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务端启动成功");
while(true) {
System.out.println("selector阻塞");
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
if(key.isAcceptable()) {
ServerSocketChannel sc = (ServerSocketChannel) key.channel();
SocketChannel accept = sc.accept();
accept.configureBlocking(false);
accept.register(selector, SelectionKey.OP_READ);
System.out.println("客户端连接成功:"+accept.getRemoteAddress());
}else if(key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer allocate = ByteBuffer.allocate(128);
int read = sc.read(allocate);
if(read>0) {
System.out.println("接收到消息:"+new String(allocate.array(),Charset.forName("GBK")));
}else if(read == -1) {
iterator.remove();
System.out.println("客户端断开了");
}
}
}
iterator.remove();
}
}
}
其中我们能获取到ServerSocketChannel 和 SocketChannel对象,而NioServerSocketChannel可以简单理解成ServerSocketChannel 的封装
通过channel注册到io.netty.bootstrap.AbstractBootstrap#channelFactory属性当中
在io.netty.bootstrap.AbstractBootstrap#bind(java.net.SocketAddress)的io.netty.bootstrap.AbstractBootstrap#initAndRegister方法中 通过反射的方式实例化NioServerSocketChannel对象 调用它的无参构造函数


无参构造函数如下:
public NioServerSocketChannel() {
//1.newSocket 2.调用当前的一个参数构造方法
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
private static ServerSocketChannel newSocket(SelectorProvider provider) { try { return provider.openServerSocketChannel();//创建nio的ServerSocketChannel对象 } catch (IOException e) { ... } }public NioServerSocketChannel(ServerSocketChannel channel) { super(null, channel, SelectionKey.OP_ACCEPT);//注册OP_ACCEPT事件 config = new NioServerSocketChannelConfig(this, javaChannel().socket()); }
io.netty.channel.nio.AbstractNioChannel#AbstractNioChannel
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) { super(parent); this.ch = ch; this.readInterestOp = readInterestOp;//设置感兴趣事件为OP_ACCEPT事件 try { ch.configureBlocking(false);//设置为非阻塞 } catch (IOException e) { ... } }
查看其它重要的方法:
protected void doBind(SocketAddress localAddress) throws Exception {//绑定端口号
if (PlatformDependent.javaVersion() >= 7) {
javaChannel().bind(localAddress, config.getBacklog());//获取ServerSocketChannel对象并绑定端口号
} else {
javaChannel().socket().bind(localAddress, config.getBacklog());
}
}
protected void doClose() throws Exception {//关闭ServerSocketChannel通道
javaChannel().close();
}
protected int doReadMessages(List<Object> buf) throws Exception {//读消息
SocketChannel ch = SocketUtils.accept(javaChannel());//accept获取SocketChannel对象 nio操作
try {
if (ch != null) {
buf.add(new NioSocketChannel(this, ch));//将socketChannel包装成 NioSocketChannel 并设置感兴趣事件OP_READ
return 1;
}
} catch (Throwable t) {
logger.warn("Failed to create a new channel from an accepted socket.", t);
try {
ch.close();
} catch (Throwable t2) {
logger.warn("Failed to close a socket.", t2);
}
}
return 0;
}
总结一:
1、 netty在main线程启动的时候创建了NioServerSocketChannel对象,也就ServerSocketChannel对象,后续在bind方法里面 netty会把这个NioServerSocketChannel注册到BossGroup的NioEventLoop对象中的Selector对象上,启动该线程 然后去监听OP_ACCEPT事件,等待客户端的连接
2、给ServerSocketChannel绑定端口号
3、BossGroup线程组的读消息,生成客户端的SocketChannel 并包装成NioSocketChannel对象
查看继承关系图NioServerSocketChannel还继承了AbstractNioMessageChannel

分析AbstractNioMessageChannel源码:
//创建了NioMessageUnsafe的unsafe实现类
protected AbstractNioUnsafe newUnsafe() {
return new NioMessageUnsafe();
}
protected void doBeginRead() throws Exception {//开始读
if (inputShutdown) {
return;
}
super.doBeginRead();//设置selectionKey感兴趣的事件 bossgroup就是OR_ACCEPT事件
}
private final class NioMessageUnsafe extends AbstractNioUnsafe {
private final List<Object> readBuf = new ArrayList<Object>();//readBuf缓存NioSocketChannel对象
@Override
public void read() {
assert eventLoop().inEventLoop();
final ChannelConfig config = config();//获取NioServerSocketChannel的config变量
final ChannelPipeline pipeline = pipeline();//获取bossGroup的pipeline
final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
allocHandle.reset(config);
boolean closed = false;
Throwable exception = null;
try {
try {
do {
int localRead = doReadMessages(readBuf);//获取read返回对象 创建NioSocketChannel事件 设置到readBuf中
if (localRead == 0) {
break;
}
if (localRead < 0) {
closed = true;
break;
}
allocHandle.incMessagesRead(localRead);
} while (continueReading(allocHandle));
} catch (Throwable t) {
exception = t;
}
//readBuf缓存NioSocketChannel对象
int size = readBuf.size();
for (int i = 0; i < size; i ++) {
readPending = false;
pipeline.fireChannelRead(readBuf.get(i));//执行DefaultChannelPipeline中的fireChannelRead方法 readbuf中存放的是NioSocketChannel等对象
}
readBuf.clear();
allocHandle.readComplete();
pipeline.fireChannelReadComplete();
if (exception != null) {
closed = closeOnReadError(exception);
pipeline.fireExceptionCaught(exception);
}
if (closed) {
inputShutdown = true;
if (isOpen()) {
close(voidPromise());
}
}
} finally {
if (!readPending && !config.isAutoRead()) {
removeReadOp();
}
}
}
...
}
总结二:
AbstractNioMessageChannel大概干了几件事情:
1、创建unsafe对象,操作io读写事件;
2、修改NioServerSocketChannel的 selectionKey感兴趣事件为OP_ACCEPT bossGroup开始监听
OP_ACCEPT请求
3、io.netty.channel.nio.AbstractNioMessageChannel.NioMessageUnsafe#read 开始读,bossGroup的线程监听OP_ACCEPT请求,当请求过来时,读事件触发,获取SocketChannel,继而封装成NioSocketChannel
1万+




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



