Here you can find the source of blockingRead(SocketChannel so, long timeout, int bytes)
public static ByteBuffer blockingRead(SocketChannel so, long timeout, int bytes) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class Main { public static ByteBuffer blockingRead(SocketChannel so, long timeout, int bytes) throws IOException { return blockingRead(so, timeout, new byte[bytes]); }/* w w w .j a v a 2s. co m*/ 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; } }