[英]Java NIO: Read data from Channel which does not contain any data. How do I handle this situation?
下面的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();
}
如果您不希望read
被阻止,則需要將您的頻道配置為非阻止 。 否則,它將坐下來等數據可用。 您可以在此處閱讀有關非阻塞NIO的更多信息。
channel.configureBlocking(false);
這是一種阻止方法。 您期望什么?
您可以在基礎套接字上設置讀取超時,也可以將通道置於非阻塞模式,可能與選擇器一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.