NIO 2.0引入了新的異步通道的概念,與之前非阻塞IO(NIO)不同的是,NIO 2.0異步套接字通道是真正的異步非阻塞I/O,對應於UNIX網絡編程中的事件驅動I/O(AIO)。它不需要通過多路複用器對註冊的通道進行輪詢操作即可實現異步讀寫,從而簡化了NIO的編程模型。話不多說,直接代碼實踐。
AIO服務端
package com.ph.AIO;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
/**
* Create by PH on 2018/11/3
*/
public class AIOServer {
public static void main(String[] args) throws IOException {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//採用默認值
}
}
//啓用服務端線程
new Thread(new AsyncServer(port), "server-01").start();
}
}
class AsyncServer implements Runnable {
private int port;
CountDownLatch latch;
AsynchronousServerSocketChannel asynchronousServerSocketChannel;
public AsyncServer(int port) {
this.port = port;
try {
// 創建一個異步服務端通道
asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
// 綁定監聽端口
asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
System.out.println("The server is start in port :" + port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
latch = new CountDownLatch(1);
doAccept();
try {
//讓線程在此阻塞,防止服務端執行完成退出
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void doAccept() {
//第一個參數爲服務端對象,第二個參數是回調對象
asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
}
}
class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncServer> {
/**
* 新的客戶端接入成功後調用
*/
public void completed(AsynchronousSocketChannel result, AsyncServer attachment) {
//繼續接受其他客戶端連接
attachment.asynchronousServerSocketChannel.accept(attachment, this);
//預分配1M緩衝區
ByteBuffer buffer = ByteBuffer.allocate(1024);
//第一個參數爲接受緩衝區,用於從異步Channel讀取數據包
//回調時的參數
//回調對象
result.read(buffer, buffer, new ReadCompletionHandler(result));
}
/**
* 新客戶端接入失敗後調用
* @param exc
* @param attachment
*/
public void failed(Throwable exc, AsyncServer attachment) {
exc.printStackTrace();
attachment.latch.countDown();
}
}
class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
private AsynchronousSocketChannel channel;
public ReadCompletionHandler(AsynchronousSocketChannel channel) {
this.channel = channel;
}
public void completed(Integer result, ByteBuffer attachment) {
//將limit置爲position,position置爲0
attachment.flip();
//remaining()返回limit - position,即可讀字節長度
byte[] body = new byte[attachment.remaining()];
//將緩衝區數據讀到body中
attachment.get(body);
try {
String req = new String(body, "UTF-8");
System.out.println("Server receive :" + req);
//向客戶端發送消息
doWrite("Server message");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void doWrite(String msg) {
if(msg != null && msg.trim().length()>0){
byte[] bytes = msg.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
writeBuffer.flip();
//與read的參數類似
channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
//如果沒有發送完成,繼續發送
if(attachment.hasRemaining()) {
channel.write(attachment, attachment, this);
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
channel.close();
}catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
public void failed(Throwable exc, ByteBuffer attachment) {
try {
this.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AIO客戶端
package com.ph.AIO;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
/**
* Create by PH on 2018/11/3
*/
public class AIOClient {
public static void main(String[] args) throws IOException {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//採用默認值
}
}
//啓用服務端線程
new Thread(new AsyncClient("127.0.0.1",port), "Client-01").start();
}
}
class AsyncClient implements CompletionHandler<Void, AsyncClient>, Runnable {
private AsynchronousSocketChannel client;
private String host;
private int port;
private CountDownLatch latch;
public AsyncClient(String host, int port) {
this.host = host;
this.port = port;
try {
client = AsynchronousSocketChannel.open();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
latch = new CountDownLatch(1);
client.connect(new InetSocketAddress(host, port), this, this);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void failed(Throwable exc, AsyncClient attachment) {
try {
this.client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void completed(Void result, AsyncClient asyncClient) {
byte[] req = "CLIENT TEST".getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
//向服務端發送消息
client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
//如果沒有發送完繼續發送,反之則等待接受服務端消息
if (attachment.hasRemaining()) {
client.write(attachment, attachment, this);
} else {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] bytes = new byte[attachment.remaining()];
attachment.get(bytes);
String body;
try {
body = new String(bytes, "UTF-8");
System.out.println("Client receive :" + body);
latch.countDown();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
client.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
client.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}