2011-08-03 51 views
3

我想了解的代碼插座和DataInputStream所

 DataInputStream stream = 
      new DataInputStream(
      new ByteArrayInputStream(messageBuffer)); 


     int  messageLength = stream.readInt(); 
     char recordType  = (char) stream.readByte(); 
     byte padding   = stream.readByte(); 
     short numberRecords = stream.readShort(); 

messageBuffer初始化爲新的字節[32768]作爲經由Socket.read()方法填充此片段。 我不明白的是一旦messageLength被初始化爲stream.readInt(),第二個第二條語句如何工作,即recordType?

第一條語句從字節數組的開頭讀取一個int,而下一條語句從字節數組的開頭讀取一個字節?它究竟從什麼地方知道讀取字節,整數,短褲等?

回答

5

documentation

ByteArrayInputStream包含一個包含字節 可以從流中讀取的內部緩衝區。 內部計數器跟蹤 下一個將由read方法提供的字節。

換句話說,DataInputStream簡單地從ByteArrayInputStream讀取,而後者會記住字節數組中的當前位置和每一些數據已被讀出時間前進了。

+0

謝謝。我正在查看DataInputStream的文檔。 – ziggy

3

DataInputStream.read*方法消耗來自基本輸入流字節。在這種情況下,read*方法讀取由ByteArrayInputStream提供的下一個可用字節,它將跟蹤陣列中的當前位置。


作爲一個側面說明,你可能要考慮使用ByteBuffer.wrap和各種ByteBuffer.read方法:

ByteBuffer msgBuf = ByteBuffer.wrap(messageBuffer); 
int messageLength = msgBuf.getInt(); 
char recordType = msgBuf.getChar(); 
... 
+0

謝謝。我正在看的代碼是非常舊的代碼,我懷疑我可能會修改它。 – ziggy

3

readX()不從流的開始讀取。實際上,術語用於表示隨時間變化可用的數據序列。這意味着從流中讀取不同的元素。

將流視爲信息傳送帶而不是陣列。

1

Socket.read()將讀取可用的字節。最小值是一個字節!最大值是緩衝區大小,其中可以包含任何數量的消息。

而不是手動讀取緩衝區,使用DataInputStream/BufferedInputStream更安全,更簡單,更高效。

// create an input stream once per socket. 
DataInputStream stream = 
     new DataInputStream(
     new BufferedInputStream(socket.getInputStream())); 


int  messageLength = stream.readInt(); 
char recordType  = (char) stream.readByte(); 
byte padding   = stream.readByte(); 
short numberRecords = stream.readShort();