前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java网络编程 -- AIO异步网络编程

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

作者头像
CodingDiray
发布2019-09-25 16:20:19
8850
发布2019-09-25 16:20:19
举报
文章被收录于专栏:Coding DiaryCoding Diary

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服务端代码示例:

代码语言:javascript
复制
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<AsynchronousSocketChannel, Object>() {
          @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<Integer, ByteBuffer>() {
                    @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客户端代码示例:

代码语言:javascript
复制
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();
  }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Coding Diary 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档