Java NIO:从Channel读取不包含任何数据的数据。我该如何处理这种情况?

时间:2012-07-24 08:02:39

标签: java sockets nio socketchannel

下面的Java代码:

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();
    }
}

这段代码很简单。

但是我没有向Channel写任何数据,因此,它不包含任何要读取的数据。

在这种情况下,方法channel.read()执行太长并且不会返回任何数据。

我该如何处理这种情况?

感谢。

2 个答案:

答案 0 :(得分:6)

更新: 查看您的示例,您正在连接到Web服务器。在您告诉它您想要做什么之前,Web服务器不会响应。例如,执行GET请求。

示例(没有正确的字符编码):

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();
}

如果您不希望read被阻止,则需要configure your channel as non-blocking。否则它将等待数据可用。您可以阅读有关非阻止NIO here的更多信息。

channel.configureBlocking(false);

答案 1 :(得分:3)

这是一种阻止方法。你有什么期望?

您可以在底层套接字上设置读取超时,也可以将通道置于非阻塞模式,可能与选择器一起使用。