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

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

문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top