public ByteBuffer readLengthAndData ( SocketChannel ch ) throws Exception { if ( bufs [ 0 ] . hasRemaining ( ) && ch . read ( bufs [ 0 ] ) < 0 ) throw new EOFException ( ) ; if ( bufs [ 0 ] . hasRemaining ( ) ) return null ; int len = bufs [ 0 ] . getInt ( 0 ) ; if ( bufs [ 1 ] == null || len > bufs [ 1 ] . capacity ( ) ) bufs [ 1 ] = ByteBuffer . allocate ( len ) ; bufs [ 1 ] . limit ( len ) ; if ( bufs [ 1 ] . hasRemaining ( ) && ch . read ( bufs [ 1 ] ) < 0 ) throw new EOFException ( ) ; if ( bufs [ 1 ] . hasRemaining ( ) ) return null ; try { return ( ByteBuffer ) bufs [ 1 ] . duplicate ( ) . flip ( ) ; } finally { bufs [ 0 ] . clear ( ) ; bufs [ 1 ] . clear ( ) ; } }
Reads length and then length bytes into the data buffer which is grown if needed .