Java网络编程 -- AIO异步网络编程

AIO中的A即Asynchronous,AIO即异步IO。它是异步非阻塞的,客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理,一般我们的业务处理逻辑会变成一个回调函数,等待IO操作完成后,由系统自动触发。

在进行读写操作时,只需直接调用API的read/write方法即可。这两种方法均为异步的,对于读操作而言,当有流可读取时,操作系统会将可读的流传入read方法的缓冲区,并通知应用程序;对于写操作而言,当操作系统将write方法传递的流写入完毕时,操作系统主动通知应用程序。即可以理解为,read/write方法都是异步的,完成后会主动调用回调函数。

AIO其实是对NIO的增强,新增了许多支持异步的类如AsynchronousServerSocketChannel,AsynchronousChannel,AsynchronousChannelGroup,CompletionHandler等。

在Linux系统中AIO和NIO的底层实现都是epoll,epoll本身是轮询模型,AIO只不过是对epoll又包了一层,而在windows系统中AIO是通过IOCP(完成端口)实现。而目前大多数的服务器都是Linux系统,这也是Netty中使用NIO而非AIO的一个原因,在实际使用中由于操作系统的差异,AIO的性能有时并没有NIO高效,因此AIO的使用并没有很广泛。

AIO服务端代码示例:

public class AIOServer {

  public static void main(String[] args) throws IOException {

    // 多线程版本
    //    ExecutorService executorService = Executors.newCachedThreadPool();
    //    AsynchronousChannelGroup channelGroup =
    //        AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
    //      AsynchronousServerSocketChannel serverSocketChannel =
    //              AsynchronousServerSocketChannel.open(channelGroup).bind(new
    // InetSocketAddress(8080));

    // 单线程版本
    AsynchronousServerSocketChannel serverSocketChannel =
        AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8080));

    serverSocketChannel.accept(
        null,
        new CompletionHandler() {
          @Override
          public void completed(AsynchronousSocketChannel client, Object attachment) {
            serverSocketChannel.accept(null, this);
            try {
              System.out.println(client.getRemoteAddress());
              ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
              client.read(
                  byteBuffer,
                  byteBuffer,
                  new CompletionHandler() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                      attachment.flip();
                      byte[] content = new byte[attachment.limit()];
                      attachment.get(content);
                      System.out.println(new String(content));
                      try {
                        System.out.println("Client: " + client.getRemoteAddress());
                      } catch (IOException e) {
                        e.printStackTrace();
                      }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                      System.out.println("failed: " + exc.getMessage());
                    }
                  });

            } catch (Exception e) {
              e.printStackTrace();
            }
          }

          @Override
          public void failed(Throwable exc, Object attachment) {}
        });

    while (true) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

AIO客户端代码示例:

public class AIOClient {

  public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
    socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
    Thread.sleep(1000);
    ByteBuffer buffer = ByteBuffer.wrap("Hello Server".getBytes());
    socketChannel.write(buffer).get();
  }
}

Java网络编程 -- AIO异步网络编程_第1张图片

转载于:https://www.cnblogs.com/coding-diary/p/11426575.html

你可能感兴趣的:(Java网络编程 -- AIO异步网络编程)