libthrift0.9.0解析(三)之TProtocol&TTransport

libthrift0.9.0解析(三)之TProtocol&TTransport   libthrift0.9.0解析(三)之TProtocol&TTransport

 

以上是transport和protocol的类图和结构图。

transport封装了底层的传输通道,主要有read/write、open/close等基本的读写方法,而且都是对于二进制数据。

protocol则对应了thrift中的各种数据结构的读写,底层调用transport。

TIOStreamTransport封装了inputStream和outputStream,TSocket封装了Socket对象,使用了socket的inputStream和outputStream:

 socket_.connect(new InetSocketAddress(host_, port_), timeout_);

 inputStream_ = new BufferedInputStream(socket_.getInputStream(), 1024);

 outputStream_ = new BufferedOutputStream(socket_.getOutputStream(), 1024);

 TBinaryProtocol以二进制的形式读写数据,举例如下:

// 写入整数

private byte[] i32out = new byte[4];

  public void writeI32(int i32) throws TException {

    i32out[0] = (byte)(0xff & (i32 >> 24));

    i32out[1] = (byte)(0xff & (i32 >> 16));

    i32out[2] = (byte)(0xff & (i32 >> 8));

    i32out[3] = (byte)(0xff & (i32));

    trans_.write(i32out, 0, 4);

  }



// 读取整数

private byte[] i32rd = new byte[4];

  public int readI32() throws TException {

    byte[] buf = i32rd;

    int off = 0;



    if (trans_.getBytesRemainingInBuffer() >= 4) {

      buf = trans_.getBuffer();

      off = trans_.getBufferPosition();

      trans_.consumeBuffer(4);

    } else {

      readAll(i32rd, 0, 4);

    }

    return

      ((buf[off] & 0xff) << 24) |

      ((buf[off+1] & 0xff) << 16) |

      ((buf[off+2] & 0xff) <<  8) |

      ((buf[off+3] & 0xff));

  }

 其中的TMessage类型数据代表了包头,name成员描述了函数名称,type成员描述了消息类型,seqid应该是此次对话的唯一id。

你可能感兴趣的:(protocol)