private void readBuffer(long timeout, long startTime, SelectionKey readKey, ByteBuffer buffer) throws IOException {
        boolean firstTime = true;
        while (currentTime() - startTime < timeout && buffer.position() != buffer.capacity()) {
            if (!firstTime) {
                long waitDuration = startTime + timeout - currentTime();
                if (waitDuration > 0) {
                    selector.select(waitDuration);
                }
            }

            if (firstTime || selector.selectedKeys().size() > 0) {
                int read;
                do {
                    read = socketChannel.read(buffer);
                } while (read > 0);

                if (firstTime) {
                    firstTime = false;
                } else {
                    selector.selectedKeys().remove(readKey);
                }
            }
        }
    }