Java NIO.2 Gurus could anyone explain why this code not working when I'm commenting out the Thread.sleep(...) line.
And what is the elegant way, to tell JVM to proccess asynchronous operations until program finishes?
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();
}
}
}
Thanks in advance.