Java教程

netty源码之读取数据

本文主要是介绍netty源码之读取数据,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录

前话

1、读数据的技巧

2、简约流程

3、读数据的本质

流程

1、读取数据


前话

1、读数据的技巧

 

 

2、简约流程

 

3、读数据的本质

 

流程

读数据的轮询和接收连接是一样的 ,都是在NioEventLoop对象的run方法里,但是在最终读的时候,调用了另外一个对象,AbstractNioByteChannel.read 方法

1、读取数据

//AbstractNioByteChannel 
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();
        }
    }
}
​
 protected int doReadBytes(ByteBuf byteBuf) throws Exception {
        final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
        allocHandle.attemptedBytesRead(byteBuf.writableBytes());
        return byteBuf.writeBytes(javaChannel(), allocHandle.attemptedBytesRead());
    }

这篇关于netty源码之读取数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!