// Create client-side I/O event dispatch
final IOEventDispatch ioEventDispatch = new DefaultClientIODispatch(protocolHandler, params);
// Create client-side I/O reactor
IOReactorConfig config = new IOReactorConfig();
config.setIoThreadCount(1);
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
// Create HTTP connection pool
BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
// Limit total number of connections to just two
pool.setDefaultMaxPerRoute(2);
pool.setMaxTotal(2);
// Run the I/O reactor in a separate thread
Thread t = new Thread(new Runnable() {
public void run() {
try {
// Ready to go!
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
// Start the client thread
t.start();
// Create HTTP request executor
HttpAsyncRequestExecutor executor = new HttpAsyncRequestExecutor(
httpproc, new DefaultConnectionReuseStrategy(), params);
// Execute HTTP GETs to the following hosts and
HttpHost[] targets = new HttpHost[] {
new HttpHost("www.apache.org", 80, "http"),
new HttpHost("www.verisign.com", 443, "https"),
new HttpHost("www.google.com", 80, "http")
};
final CountDownLatch latch = new CountDownLatch(targets.length);
for (final HttpHost target: targets) {
BasicHttpRequest request = new BasicHttpRequest("GET", "/");
executor.execute(
new BasicAsyncRequestProducer(target, request),
new BasicAsyncResponseConsumer(),
pool,
new BasicHttpContext(),
// Handle HTTP response from a callback
new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(target + "->" + response.getStatusLine());
}
public void failed(final Exception ex) {
latch.countDown();
System.out.println(target + "->" + ex);
}
public void cancelled() {
latch.countDown();
System.out.println(target + " cancelled");
}
});
}
latch.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}