Java中怎么实现AIO异步网络编程

发布时间:2021-06-30 17:24:53 作者:Leah
来源:亿速云 阅读:136

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<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客户端代码示例:

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. java中怎么实现同步与异步
  2. Java中BIO、NIO、AIO的理解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:什么是php适配器模式

下一篇:如何使用一个for循环将N*N的二维数组的所有值置1

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》