SocketChannel分为两种:
1、NioSocketChannel
2、NioServerSocketChannel
让我们用一个简化的类图来看看他们的关系:
最终他们都继承自Channel,这个Channel是netty定义的,Channel定义了子类的规范。
AbstractChannel对Channel做了抽象的实现:
private final Channel parent;
private final ChannelId id;
private final Unsafe unsafe;
private final DefaultChannelPipeline pipeline;
还有重要的EventLoop也是在这个类里面抽象出来的。
这些东西都是在AbstractChannel这里定义的。
接下去是AbstractNioChannel:
/**
* Abstract base class for {@link Channel} implementations which use a Selector based approach.
*/
public abstract class AbstractNioChannel extends AbstractChannel {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(AbstractNioChannel.class);
private static final ClosedChannelException DO_CLOSE_CLOSED_CHANNEL_EXCEPTION = ThrowableUtil.unknownStackTrace(
new ClosedChannelException(), AbstractNioChannel.class, "doClose()");
private final SelectableChannel ch;
protected final int readInterestOp;
volatile SelectionKey selectionKey;
boolean readPending;
...
}
这个类:Abstract base class for {@link Channel} implementations which use a Selector based approach.,也就是使用了Selector来做为实现读写的监听。
在这里,实现了几个重要的抽象:
private final SelectableChannel ch;
protected final int readInterestOp;
volatile SelectionKey selectionKey;
ch就是jdk底层的channel,readInterestOp感兴趣的事件,selectionKey。
这个类开始,下面就做两个实现,一个是AbstractNioByteChannel,客户端Channel的父类,因为它只关心读(read)事件,组合在里面的unsafe是NioByteUnsafe,他的配置类是NioSocketChannelConfig;另一个是AbstarctNioMessageChannel,服务端Channel的父类,因为是服务端,所以只关心accept事件,组合在里面的unsafe是NioMessageUnsafe,他的配置类是NioServerSocketChannelConfig。后面的config,主要就是处理一些tcp连接的配置。
有兴趣的看源码,也很简单,这里主要简单介绍下而已。