Example usage for java.nio.channels SocketChannel read

List of usage examples for java.nio.channels SocketChannel read

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel read.

Prototype

public final long read(ByteBuffer[] dsts) throws IOException 

Source Link

Usage

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);//www  .  j  av a  2s.  co m

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:Main.java

public static String processRead(SelectionKey key) throws Exception {
    SocketChannel sChannel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    sChannel.read(buffer);
    buffer.flip();/*from w  w w  .  jav a 2s.c o m*/
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);
    String msg = charBuffer.toString();
    return msg;
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();/*from ww w . j  av  a2  s. c  o m*/
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:gridool.communication.transport.tcp.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();// w  w  w. jav a  2  s .co m
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private static String readFromSocket(SocketChannel client) throws IOException {
    ByteBuffer readBuf = ByteBuffer.allocate(256);
    LOG.info("Reading from client");
    client.read(readBuf);
    readBuf.flip();//from   ww  w.j  a v  a2s  .  co  m
    return StandardCharsets.US_ASCII.decode(readBuf).toString();
}

From source file:com.facebook.infrastructure.net.io.StartState.java

protected byte[] doRead(ByteBuffer buffer) throws IOException, ReadNotCompleteException {
    SocketChannel socketChannel = stream_.getStream();
    int bytesRead = socketChannel.read(buffer);
    if (bytesRead == -1 && buffer.remaining() > 0) {
        throw new IOException("Reached an EOL or something bizzare occured. Reading from: "
                + socketChannel.socket().getInetAddress() + " BufferSizeRemaining: " + buffer.remaining());
    }// w w w  . ja v a2 s  .  c o  m
    if (buffer.remaining() == 0) {
        morphState();
    } else {
        throw new ReadNotCompleteException(
                "Specified number of bytes have not been read from the Socket Channel");
    }
    return ArrayUtils.EMPTY_BYTE_ARRAY;
}

From source file:idgs.client.SocketChannelHandler.java

/**
 * handle read message/*from   ww  w . j av  a2  s  .  c  o  m*/
 * @param channel
 * @param ctx
 * @throws IOException
 */
public void onRead(SocketChannel channel) throws IOException {
    RpcBuffer buffer = new RpcBuffer();
    buffer.decodeHeader(); // allocate default header size
    // read header
    int headerTotalBytes = 0, nBytes = 0;
    while (buffer.hasRemaining() && (nBytes = channel.read(buffer.getBody())) > 0) {
        headerTotalBytes += nBytes;
    }
    buffer.flip();
    if (headerTotalBytes > 0) {
        assert (headerTotalBytes == buffer.getBodyLength());
        int bodyLength = buffer.getBody().getInt();
        log.debug("read header content: " + bodyLength);
        log.debug("byte size: " + headerTotalBytes + ", order by " + buffer.getByteOrder().toString()
                + " bytes: " + Arrays.toString(buffer.array()));
        buffer.setBodyLength(bodyLength);
        buffer.decodeHeader(); // decode header
        int bodyTotalBytes = 0;
        while (buffer.hasRemaining()) {
            nBytes = channel.read(buffer.getBody());
            if (nBytes == -1) {
                log.error("read end of stream");
                throw new IOException("read end of stream");
            }
            bodyTotalBytes += nBytes;
        }
        buffer.flip();
        // read body
        if (bodyTotalBytes > 0) {
            assert (bodyTotalBytes == buffer.getBodyLength());
            RpcMessage.Builder builder = RpcMessage.newBuilder();
            byte[] bytes = buffer.array();
            ProtoSerdeFactory.createSerde(builder.getSerdesType().getNumber()).deserializeFromByteArray(builder,
                    bytes);
            //        log.debug("read body content: " + new String(bytes));
            log.debug("byte size: " + bodyTotalBytes + ", order by " + buffer.getByteOrder().toString()
                    + " bytes: " + Arrays.toString(bytes));
            context.setAttachment(new ClientActorMessage(builder));
        } else {
            log.warn("read body nothing");
        }
    } else {
        log.warn("read header nothing");
    }
}

From source file:org.reunionemu.jreunion.server.Network.java

private boolean processInput(SocketChannel socketChannel) {

    int result = -1;
    Client client = null;//w  ww.ja  va2 s  .  co m
    buffer.clear();
    try {
        result = socketChannel.read(buffer);
        buffer.flip();
        client = Server.getInstance().getWorld().getClients().get(socketChannel);
    } catch (IOException e) {
        LoggerFactory.getLogger(this.getClass()).error("Exception", e);
    }

    // If no data or client, close the connection
    if (result <= 0 || client == null) {
        return false;
    }

    byte[] data = new byte[result];
    buffer.get(data, 0, result);

    fireEvent(NetworkDataEvent.class, socketChannel, data);

    return true;
}

From source file:reactor.io.net.http.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {// w  w w.  j  a  v  a  2  s .  c  om
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(Buffer.wrap(request.toString()).byteBuffer());
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:reactor.io.netty.http.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {//from   w w  w.  j  av a 2s .c o m
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}