Reads a single byte from a SocketChannel - Java java.nio.channels

Java examples for java.nio.channels:SocketChannel

Description

Reads a single byte from a SocketChannel

Demo Code


//package com.java2s;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {
    /** Reads a single byte from a channel */
    public static byte getByte(SocketChannel c) throws IOException {
        ByteBuffer b = readBytes(c, 1);
        return b.get();
    }//ww  w . j av  a 2s.  co m

    /** Reads a certain number of bytes from the stream.
     * 
     * Makes 10 attempts to fill the buffer before throwing an exception.
     * 
     * @param c Channel to read from
     * @param length Number of bytes to read
     * @return A full byte buffer of the given length
     * @throws IOException if the socket closes early, can't get enough to read, or has another read issue
     */
    public static ByteBuffer readBytes(SocketChannel c, int length)
            throws IOException {
        ByteBuffer b = ByteBuffer.allocateDirect(length);
        int retries = 10;
        while (b.remaining() > 0 && retries > 0) {
            int read = c.read(b);
            if (read < 0) {
                c.close();
                throw new IOException("Socket closed early.");
            }
            retries--;
        }
        if (retries <= 0)
            throw new IOException("Not enough data to read");
        b.flip();
        return b;
    }
}

Related Tutorials