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

Java examples for java.nio.channels:SocketChannel

Description

Reads a single double 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 double from a channel */
    public static double getDouble(SocketChannel c) throws IOException {
        ByteBuffer b = readBytes(c, 8);
        return b.getDouble();
    }/*from   w  w  w  .ja  v 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