TTransport 概述


TTransport

TTransport主要作用是定義了IO讀寫操作以及本地緩存的操作,下面來看TIOStreamTransport是如何實現的。

public abstract class TTransport implements Closeable {

  //當前連接是否已打開
  public abstract boolean isOpen();

  //是否還有數據需要讀,當連接關閉時認為無數據可讀
  public boolean peek() {
    return isOpen();
  }

  //打開當前連接,可用於IO讀寫
  public abstract void open()
    throws TTransportException;

  //關閉當前連接
  public abstract void close();

  //向buf字節數組中寫入數據,從off開始,最多讀len長度的字節,最后返回實際向buf寫入的字節數
  public abstract int read(byte[] buf, int off, int len)
    throws TTransportException;

   //確保向buf中從off開始寫入,len長度的字節,這里通過循環調用上面的方法實現最后返回向buf寫入的字節數
  public int readAll(byte[] buf, int off, int len)
    throws TTransportException {
    int got = 0;
    int ret = 0;
    //沒有讀完繼續下一次讀取,直接讀到的數據大於等於需要的len長度
    while (got < len) {
      ret = read(buf, off+got, len-got);
      if (ret <= 0) {
        throw new TTransportException(
            "Cannot read. Remote side has closed. Tried to read "
                + len
                + " bytes, but only got "
                + got
                + " bytes. (This is often indicative of an internal error on the server side. Please check your server logs.)");
      }
      got += ret;
    }
    return got;
  }

  //將buf中的數據全部發送出去
  public void write(byte[] buf) throws TTransportException {
    write(buf, 0, buf.length);
  }

  //將buf的數據,從off開始,發送len長度的數據出去
  public abstract void write(byte[] buf, int off, int len)
    throws TTransportException;
    
  
  
  //下面四個方法,與ByteBuffer的原理類似
  //獲取到本地緩存的數據,沒有緩存直接返回空
  public byte[] getBuffer() {
    return null;
  }

  //返回本地緩存下一個讀取位置,沒有緩存返回0即可
  public int getBufferPosition() {
    return 0;
  }

  //獲取本地緩存中的字節數,沒有緩存返回-1
  public int getBytesRemainingInBuffer() {
    return -1;
  }

  //從本地緩存中消費n個字節
  public void consumeBuffer(int len) {}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM