设为首页 加入收藏

TOP

到底什么是Java AIO?为什么Netty会移除AIO?一文搞懂AIO的本质!(二)
2023-09-09 10:25:54 】 浏览:85
Tags:Java AIO Netty 文搞懂
是原来的线程;
  • 2)而NIO也称之为同步,原因也是如此,调用channel.read()时,线程虽然不会阻塞,但读到数据的还是当前线程。

  • 按照这个思路,AIO应该是发起IO读写的线程,和实际收到数据的线程,可能不是同一个线程。

    是不是这样呢?我们将在上一节直接上Java AIO的代码,我们从 实际代码中一窥究竟吧。

    4、一个Java AIO的网络编程示例


    4.1AIO服务端程序代码

      public class AioServer {
     
         public static void main(String[] args) throws IOException {
             System.out.println(Thread.currentThread().getName() + " AioServer start" );
             AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open()
                     .bind( new InetSocketAddress( "127.0.0.1" , 8080 ));
             serverChannel.accept( null , new CompletionHandler<AsynchronousSocketChannel, Void>() {
     
                 @Override
                 public void completed(AsynchronousSocketChannel clientChannel, Void attachment) {
                     System.out.println(Thread.currentThread().getName() + " client is connected" );
                     ByteBuffer buffer = ByteBuffer.allocate( 1024 );
                     clientChannel.read(buffer, buffer, new ClientHandler());
                 }
     
                 @Override
                 public void failed(Throwable exc, Void attachment) {
                     System.out.println( "accept fail" );
                 }
             });
             System.in.read();
         }
    }
     
    public class ClientHandler implements CompletionHandler<Integer, ByteBuffer> {
         @Override
         public void completed(Integer result, ByteBuffer buffer) {
             buffer.flip();
             byte [] data = new byte [buffer.remaining()];
             buffer.get(data);
             System.out.println(Thread.currentThread().getName() + " received:"  + new String(data, StandardCharsets.UTF_8));
         }
     
         @Override
     
    首页 上一页 1 2 3 4 下一页 尾页 2/4/4
    】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
    上一篇Nacos源码 (5) Grpc服务端和客户端 下一篇ThreadLocal:线程中的全局变量

    最新文章

    热门文章

    Hot 文章

    Python

    C 语言

    C++基础

    大数据基础

    linux编程基础

    C/C++面试题目