Java code below:
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();
}
}
This code is easy.
But I did not write any data to Channel, so, it does not contain any data to reading.
In this case method channel.read()
performed too long and do not return any data.
How do I handle this situation?
Thanks.
It's a blocking method. What did you expect?
You can set a read timeout on the underlying socket, or you can put the channel into non-blocking mode, probably in conjunction with a Selector.