2.3Java 非同步io式(AIO)
阿新 • • 發佈:2018-12-12
Java 非同步io式(AIO)
執行流程
AIO(proactor模型):執行緒發起IO請求,立即返回;記憶體做好IO操作的準備之後,做IO操作,直到操作完成或者失敗,通過呼叫註冊的回撥函式通知執行緒做IO操作完成或者失敗。 非同步非阻塞,伺服器實現模式為一個有效請求一個執行緒,客戶端的I/O請求都是由OS先完成了再通知伺服器應用去啟動執行緒進行處理,
程式碼
1.server
public class Server {
private static Charset charset = Charset.forName("utf-8");
private static CharsetEncoder encoder = charset.newEncoder();
public static void main(String[] args) throws Exception {
AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(4));
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(group).bind(new InetSocketAddress("0.0.0.0", 8013));
server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel result, Void attachment) {
server.accept(null, this); // 接受下一個連線
try {
String now = new Date().toString();
ByteBuffer buffer = encoder.encode(CharBuffer.wrap(now + "\r\n"));
//result.write(buffer, null, new CompletionHandler<Integer,Void>(){...}); //callback or
Future<Integer> f = result.write(buffer);
f.get();
System.out.println("sent to client: " + now);
result.close();
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
group.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
}
2.client
public class Client {
public static void main(String[] args) throws Exception {
AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
Future<Void> future = client.connect(new InetSocketAddress("127.0.0.1", 8013));
future.get();
ByteBuffer buffer = ByteBuffer.allocate(100);
client.read(buffer, null, new CompletionHandler<Integer, Void>() {
@Override
public void completed(Integer result, Void attachment) {
System.out.println("client received: " + new String(buffer.array()));
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Thread.sleep(10000);
}
}