Java NIO.2 Gurusは、Thread.sleep(...)行をコメントアウトしているときに、なぜこのコードが機能しないのか説明できます。Java NIO.2 CompletetionHandlerが到達しない
そして、プログラムが終了するまで非同期操作を処理するようにJVMに指示するにはどうすればよいですか?
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class Main {
public static void main(String[] args) {
try {
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
channel.connect(new InetSocketAddress("www.yahoo.com", 80),
null, new CompletionHandler<Void, Object>() {
@Override
public void completed(Void result, Object attachment) {
System.out.println("Connected");
ByteBuffer buffer = ByteBuffer.wrap("GET http://www.yahoo.com HTTP/1.1\r\n\r\n".getBytes());
channel.write(buffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("Write completed: " + result.toString());
ByteBuffer buffer = ByteBuffer.allocate(23);
channel.read(buffer, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("Read completed: " + result.toString());
System.out.println(new String(buffer.array()));
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
}
@Override
public void failed(Throwable exc, Object attachment) {
exc.printStackTrace();
}
});
Thread.sleep(10000);
channel.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
ありがとうございます。