public static ByteBuffer blockingRead ( SocketChannel so , long timeout , byte [ ] bytes ) throws IOException { ByteBuffer b = ByteBuffer . wrap ( bytes ) ; if ( bytes . length == 0 ) return b ; final long timeoutTime = ( timeout > 0 ) ? ( System . currentTimeMillis ( ) + timeout ) : ( Long . MAX_VALUE ) ; while ( b . remaining ( ) != 0 && System . currentTimeMillis ( ) < timeoutTime ) { if ( ! so . isConnected ( ) ) throw new IOException ( "Socket closed during read operation!" ) ; so . read ( b ) ; if ( b . remaining ( ) != 0 ) { // sleep for a short time try { Thread . sleep ( 20 ) ; } catch ( InterruptedException e ) { } } } if ( System . currentTimeMillis ( ) >= timeoutTime ) { return null ; } b . rewind ( ) ; // make it easy for the caller to read from the buffer (if they're interested) return b ; }
Read a number of bytes from a socket terminating when complete after timeout milliseconds or if an error occurs