下面的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()
方法执行时间太长并且不返回任何数据。
我该如何处理这种情况?
谢谢。
最佳答案
更新:查看您正在连接到网络服务器的示例。在您告诉网络服务器您想要做什么之前,网络服务器不会响应。例如执行 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();
}
<小时/>
如果您不希望您的读取
被阻塞,您需要configure your channel as non-blocking 。否则它将等待直到数据可用。您可以阅读更多关于非阻塞 NIO here .
channel.configureBlocking(false);
关于Java NIO : Read data from Channel which does not contain any data. 我该如何处理这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11626606/