FrameBuffer是Thrift NIO服务器端的一个核心组件,它一方面承担了NIO编程中的缓冲区的功能,另一方面还承担了RPC方法调用的职责。
FrameBufferState定义了FrameBuffer作为缓冲区的读写状态
private enum FrameBufferState {
// in the midst of reading the frame size off the wire
// 读Frame消息头,实际是4字节表示Frame长度
READING_FRAME_SIZE,
// reading the actual frame data now, but not all the way done yet
// 读Frame消息体
READING_FRAME,
// completely read the frame, so an invocation can now happen
// 读满包
READ_FRAME_COMPLETE,
// waiting to get switched to listening for write events
// 等待注册写
AWAITING_REGISTER_WRITE,
// started writing response data, not fully complete yet
// 写半包
WRITING,
// another thread wants this framebuffer to go back to reading
// 等待注册读
AWAITING_REGISTER_READ,
// we want our transport and selection key invalidated in the selector
// thread
// 等待关闭
AWAITING_CLOSE
}
值得注意的是,FrameBuffer读数据时,
1. 先读4字节的Frame消息头,
2. 然后改变FrameBufferState,从READING_FRMAE_SIZE到READING_FRAME,并根据读到的Frame长度修改Buffer的长度
3. 再次读Frame消息体,如果读完就修改状态到READ_FRAME_COMPLETE,否则还是把FrameBuffer绑定到SelectionKey,下次继续读
public boolean read() {
if (state_ == FrameBufferState.READING_FRAME_SIZE) {
// try to read the frame size completely
if (!internalRead()) {
return false;
}
// if the frame size has been read completely, then prepare to read the
// actual