Java NIO: Read data from Channel which does not contain any data. How do I handle this situation?

StackOverflow https://stackoverflow.com/questions/11626606

Question

Java code below:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;

public class Test {

    public static void main(String[] args) throws IOException {

        SocketChannel channel = SocketChannel.open(new InetSocketAddress(
                "google.com", 80));

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while ((channel.read(buffer)) != -1) {

            buffer.clear();
        }

        channel.close();
    }
}

This code is easy.

But I did not write any data to Channel, so, it does not contain any data to reading.

In this case method channel.read() performed too long and do not return any data.

How do I handle this situation?

Thanks.

Was it helpful?

Solution

It's a blocking method. What did you expect?

You can set a read timeout on the underlying socket, or you can put the channel into non-blocking mode, probably in conjunction with a Selector.

OTHER TIPS

Update: Looking at your example you are connecting to a web server. The web server will not respond till you tell it what you want to do. For example doing a GET request.

Example (no proper character encoding):

public static void main(String args[]) throws IOException {

    SocketChannel channel = SocketChannel.open(
            new InetSocketAddress("google.com", 80));

    channel.write(ByteBuffer.wrap("GET / HTTP/1.1\r\n\r\n".getBytes()));

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    while ((channel.read(buffer)) != -1) {

        buffer.flip();

        byte[] bytes = new byte[buffer.limit()];
        buffer.get(bytes);
        System.out.print(new String(bytes));

        buffer.clear();
    }

    channel.close();
}

If you don't want your reads to be blocking you would need to configure your channel as non-blocking. Otherwise it will sit and wait till data is available. You can read more about non-blocking NIO here.

channel.configureBlocking(false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top