Java File Read via ByteBuffer blockingRead(SocketChannel so, long timeout, int bytes)

Here you can find the source of blockingRead(SocketChannel so, long timeout, int bytes)

Description

blocking Read

License

Open Source License

Declaration

public static ByteBuffer blockingRead(SocketChannel so, long timeout, int bytes) throws IOException 

Method Source Code


//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;
    }
}

Related

  1. channelCopy(@Nonnull @WillNotClose final ReadableByteChannel aSrc, @Nonnull @WillNotClose final WritableByteChannel aDest)
  2. channelCopy2(ReadableByteChannel src, WritableByteChannel dest)
  3. ClientReadWithBlock(SocketChannel sc)
  4. ClientReadWithWait(SocketChannel sc)