Java ByteBuffer to Int readIntoBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs)

Here you can find the source of readIntoBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs)

Description

read Into Buffer

License

BSD License

Declaration

static public int readIntoBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs) 

Method Source Code


//package com.java2s;
//License from project: BSD License 

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class Main {
    static public int readIntoBuffer(SocketChannel channel, ByteBuffer buf, int sleepMsecs) {

        if (channel == null) {
            return -1;
        }//from  w  ww  . ja v  a 2s  .c  om

        buf.clear();
        int totRead = 0;

        // read until capacity reached

        while (totRead < buf.capacity()) {

            int nRead;
            try {
                nRead = channel.read(buf);
            } catch (IOException e) {
                System.err.println("Error reading channel into buffer");
                e.printStackTrace();
                return -1;
            }
            if (nRead < 0) {
                return -1;
            }
            totRead += nRead;

            // sleep if no data available

            if (nRead == 0) {
                _sleep(sleepMsecs);
            }

        } // while

        // prepare buffer for use

        buf.rewind();

        return 0;

    }

    static private void _sleep(int msecs) {

        Thread t = Thread.currentThread();
        try {
            t.sleep(msecs);
        } catch (InterruptedException e) {
        }

    }
}

Related

  1. readInt32(ByteBuffer bb)
  2. readInt8(final ByteBuffer buffer)
  3. readIntEquals(ByteBuffer buf, int i, int j)
  4. readIntLE(ByteBuffer buf, int i)
  5. readIntMSB(ByteBuffer logBuf)
  6. readInts(final ByteBuffer bb, final int length)
  7. readInts4(final ByteBuffer buffer, final int[] array, final int count)
  8. readUnsigned(ByteBuffer in, int size)
  9. readUnsignedByte(ByteBuffer buffer)