netty读取代码分析

在NioEventLoop的run方法里面进行分发处理

netty读取代码分析_第1张图片

在processSelectedKeysOptimized获得

netty读取代码分析_第2张图片

相当于douglea提出的ReactorDesign中的

-》acceptd

-》读写的

netty读取代码分析_第3张图片

a的父类为AbstractNioChannel,进入processSelectedKey

netty读取代码分析_第4张图片

在unsafe.read中获取config、pipeline,分配内存,doReadBytes(ByteBuf byteBuf)读取数据

netty读取代码分析_第5张图片

io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read

@Override
public final void read() {
    final ChannelConfig config = config();
    final ChannelPipeline pipeline = pipeline();
    final ByteBufAllocator allocator = config.getAllocator();
    final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle();
    allocHandle.reset(config);
    ByteBuf byteBuf = null;
    boolean close = false;
    try {
        do {
            byteBuf = allocHandle.allocate(allocator);
            allocHandle.lastBytesRead(doReadBytes(byteBuf));
            if (allocHandle.lastBytesRead() <= 0) {
                // nothing was read. release the buffer.
                byteBuf.release();
                byteBuf = null;
                close = allocHandle.lastBytesRead() < 0;
                break;
            }

            allocHandle.incMessagesRead(1);
            readPending = false;
            pipeline.fireChannelRead(byteBuf);
            byteBuf = null;
        } while (allocHandle.continueReading());

        allocHandle.readComplete();
        pipeline.fireChannelReadComplete();

        if (close) {
            closeOnRead(pipeline);
        }
    } catch (Throwable t) {
        handleReadException(pipeline, byteBuf, t, close, allocHandle);
    } finally {
        // Check if there is a readPending which was not processed yet.
        // This could be for two reasons:
        // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
        // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
        //
        // See https://github.com/netty/netty/issues/2254
        if (!readPending && !config.isAutoRead()) {
            removeReadOp();
        }
    }
}

 

doReadBytes(ByteBuf byteBuf)位于NioSockerChannel里面,一个服务器端口一个SocketChannel

进入AbstractByteBuf的writeBytes的PoolUnsafeDirectByteBuf的setBytes的in.read(tmpBuf),通过SocketChannel通道读取数据

netty读取代码分析_第6张图片

netty读取代码分析_第7张图片

数据返回到io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read

pipeline.fireChannelRead(byteBuf)读数据进行解码等处理

netty读取代码分析_第8张图片

netty读取代码分析_第9张图片

如果是ChannelInboundHandler进行处理

netty读取代码分析_第10张图片

MessageToMessageDecoder处理消息类型的解码器 decode为piple中的StringDecoder

netty读取代码分析_第11张图片

你可能感兴趣的:(java)