简体   繁体   中英

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

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.

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 read s 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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM