//使用CompletionHandler来处理IO事件
// asynchronousServerSocketChannel.accept(null, new CompletionHandler()
//client使用CompletionHandler来处理IO事件
//asynchronousSocketChannel.connect(new InetSocketAddress(IP, DEFAULT_PORT), null,new CompletionHandler()
try {
final AsynchronousSocketChannel asynchronousSocketChannel = asynchronousSocketChannelFuture
.get();
Callable worker = new Callable() {
@Override
public String call() throws Exception {
String host = asynchronousSocketChannel
.getRemoteAddress().toString();
System.out.println("Incoming connection from: "
+ host);
final ByteBuffer buffer = ByteBuffer
.allocateDirect(1024);
// transmitting data
while (asynchronousSocketChannel.read(buffer)
.get() != -1) {
buffer.flip();
}
asynchronousSocketChannel.write(buffer).get();
if (buffer.hasRemaining()) {
buffer.compact();
} else {
buffer.clear();
}
asynchronousSocketChannel.close();
System.out.println(host
+ " was successfully served!");
return host;
}
};
taskExecutor.submit(worker);
} catch (InterruptedException | ExecutionException ex) {
System.err.println(ex);
System.err.println("\n Server is shutting down ...");
// this will make the executor accept no new threads
// and finish all existing threads in the queue
taskExecutor.shutdown();
// wait until all threads are finished
while (!taskExecutor.isTerminated()) {
}
break;
}
}
} else {
System.out
.println("The asynchronous server-socket channel cannot be opened!");
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
输出:
[
html]
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do something else while reading ...
Do som