Slide 26
Slide 26 text
public static void asyncNonBlockingRequest(ExecutorService executor,
String url, String headers,
RequestHandler handler) {
executor.submit(() -> {
try {
println("Starting request to " + url);
URL uri = new URL(url);
SocketAddress serverAddress = new InetSocketAddress(uri.getHost(), 80);
AsynchronousSocketChannel channel = AsynchronousSocketChannel.open(group);
channel.connect(serverAddress, null, new CompletionHandler() {
@Override
public void completed(Void result, Void attachment) {
ByteBuffer headersBuffer = ByteBuffer.wrap((headers + "Host: " +
uri.ge
ByteBuffer responseBuffer = ByteBuffer.allocate(1024);
channel.write(headersBuffer, headersBuffer, new
CompletionHandler<>() {
@Override
public void completed(Integer written, ByteBuffer attachment) {
if (attachment.hasRemaining()) {
channel.write(attachment, attachment, this);
} else {
channel.read(responseBuffer, responseBuffer, new
Completion
@Override
public void completed(Integer read,
ByteBuffer attachment) {
// More
// this
// way
// ==>