JavaNIO:从不包含任何数据的通道读取数据。我如何处理这种情况?

JavaNIO:从不包含任何数据的通道读取数据。我如何处理这种情况?,java,sockets,nio,socketchannel,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

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.read()
执行的太长,不返回任何数据

我如何处理这种情况

谢谢。

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

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


如果你不想让你的
read
s被阻塞,你需要这样做。否则,它将等待数据可用。您可以阅读更多关于非阻塞NIO的内容


这是一种阻塞方法。你期待什么


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

请您解释一下,“阻塞方法”是什么意思?@user471011我的意思正是Javadoc中所说的。在阻塞模式下,它将阻塞,直到至少一个字节的数据到达或流结束。
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();
}
channel.configureBlocking(false);