use*_*011 0 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()执行时间过长,不返回任何数据.
我该如何处理这种情况?
谢谢.
更新:查看您的示例,您将连接到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();
}
如果您不希望自己的reads被阻止,则需要将您的频道配置为非阻止.否则它将等待数据可用.您可以在此处阅读有关非阻塞NIO的更多信息.
channel.configureBlocking(false);