通道绑定活跃后激活管道的处理器
public final ChannelPipeline fireChannelActive() {
AbstractChannelHandlerContext.invokeChannelActive(head);
return this;
}
static void invokeChannelActive(final AbstractChannelHandlerContext next) {
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeChannelActive();
} else {
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeChannelActive();
}
});
}
}
private void invokeChannelActive() {
if (invokeHandler()) {
try {
((ChannelInboundHandler) handler()).channelActive(this);
} catch (Throwable t) {
notifyHandlerException(t);
}
} else {
fireChannelActive();
}
}
从头节点开始处理,每个流入类型的处理器都需要对激活事件进行处理
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();
readIfIsAutoRead();
}
public ChannelHandlerContext fireChannelActive() {
invokeChannelActive(findContextInbound());
return this;
}
头处理器判断是否自动读,默认为true
private void readIfIsAutoRead() {
if (channel.config().isAutoRead()) {
channel.read();
}
}
public boolean isAutoRead() {
return autoRead == 1;
}
开始激活网络通道读取
public Channel read() {
pipeline.read();
return this;
}
从尾结点开始,查找流出类型的处理器
public final ChannelPipeline read() {
tail.read();
return this;
}
public ChannelHandlerContext read() {
final AbstractChannelHandlerContext next = findContextOutbound();
EventExecutor executor = next.executor();
if (executor.inEventLoop()) {
next.invokeRead();
} else {
Runnable task = next.invokeReadTask;
if (task == null) {
next.invokeReadTask = task = new Runnable() {
@Override
public void run() {
next.invokeRead();
}
};
}
executor.execute(task);
}
return this;
}
依次执行读操作
private void invokeRead() {
if (invokeHandler()) {
try {
((ChannelOutboundHandler) handler()).read(this);
} catch (Throwable t) {
notifyHandlerException(t);
}
} else {
read();
}
}
public void read(ChannelHandlerContext ctx) throws Exception {
ctx.read();
}
最后一个符合条件的是头处理器,开始读取前判断网路通道是否活跃
public void read(ChannelHandlerContext ctx) {
unsafe.beginRead();
}
public final void beginRead() {
assertEventLoop();
if (!isActive()) {
return;
}
try {
doBeginRead();
} catch (final Exception e) {
invokeLater(new Runnable() {
@Override
public void run() {
pipeline.fireExceptionCaught(e);
}
});
close(voidPromise());
}
}
判断SelectionKey是否可用,设置准备读取的标志位,因为注册通道的时候设置的监听状态为0,所以这块修改为SelectionKey.OP_ACCEPT监听客户端的链接请求
protected void doBeginRead() throws Exception {
// Channel.read() or ChannelHandlerContext.read() was called
if (inputShutdown) {
return;
}
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}
readPending = true;
final int interestOps = selectionKey.interestOps();
if ((interestOps & readInterestOp) == 0) {
selectionKey.interestOps(interestOps | readInterestOp);
}
}

1820

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



