zoukankan      html  css  js  c++  java
  • java中的AIO

    AIO(异步非阻塞)AIO采用了Proactor模式,AIO与NIO的不同之处在于当AIO在进行读写操作时,不用先等通知,可直接调用相应的read/write方法,这两种方法均为异步的,对于读操作而言,当有流可读取时,操作系统会将可读的流传入read方法的缓冲区,并通知应用程序;对于写操作而言,当操作系统将write方法传递的流写入完毕时,操作系统主动通知应用程序,而NIO的通知是发生在动作之前的,是在可读、写的时候,Selector发现了这些事件后调用Handler处理.

    在AIO socket编程中,服务端通道是AsynchronousServerSocketChannel,这个类提供了一个open()静态工厂,一个bind()方法用于绑定服务端IP地址(还有端口号),另外还提供了accept()用于接收用户连接请求。在客户端使用的通道是AsynchronousSocketChannel,这个通道处理提供open静态工厂方法外,还提供了read和write方法。

    在AIO编程中,发出一个事件(accept read write等)之后要指定事件处理类(回调函数),AIO中的事件处理类是CompletionHandler<V,A>,这个接口定义了如下两个方法,分别在异步操作成功和失败时被回调。

    void completed(V result, A attachment);

     void failed(Throwable exc, A attachment);

    1. import java.io.IOException;  
    2. import java.net.InetSocketAddress;  
    3. import java.nio.ByteBuffer;  
    4. import java.nio.channels.AsynchronousServerSocketChannel;  
    5. import java.nio.channels.AsynchronousSocketChannel;  
    6. import java.nio.channels.CompletionHandler;  
    7. import java.util.concurrent.ExecutionException;  
    8. import java.util.concurrent.Future;  
    9. import java.util.concurrent.TimeUnit;  
    10. import java.util.concurrent.TimeoutException;  
    11.   
    12. public class AIOEchoServer {  
    13.   
    14.     public final static int PORT = 8001;  
    15.     public final static String IP = "127.0.0.1";  
    16.   
    17.       
    18.     private AsynchronousServerSocketChannel server = null;  
    19.       
    20.     public AIOEchoServer(){  
    21.         try {  
    22.             //同样是利用工厂方法产生一个通道,异步通道 AsynchronousServerSocketChannel  
    23.             server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(IP,PORT));  
    24.         } catch (IOException e) {  
    25.             e.printStackTrace();  
    26.         }  
    27.     }  
    28.       
    29.     //使用这个通道(server)来进行客户端的接收和处理  
    30.     public void start(){  
    31.         System.out.println("Server listen on "+PORT);  
    32.           
    33.         //注册事件和事件完成后的处理器,这个CompletionHandler就是事件完成后的处理器  
    34.         server.accept(null,new CompletionHandler<AsynchronousSocketChannel,Object>(){  
    35.   
    36.             final ByteBuffer buffer = ByteBuffer.allocate(1024);  
    37.               
    38.             @Override  
    39.             public void completed(AsynchronousSocketChannel result,Object attachment) {  
    40.                   
    41.                 System.out.println(Thread.currentThread().getName());  
    42.                 Future<Integer> writeResult = null;  
    43.                   
    44.                 try{  
    45.                     buffer.clear();  
    46.                     result.read(buffer).get(100,TimeUnit.SECONDS);  
    47.                       
    48.                     System.out.println("In server: "+ new String(buffer.array()));  
    49.                       
    50.                     //将数据写回客户端  
    51.                     buffer.flip();  
    52.                     writeResult = result.write(buffer);  
    53.                 }catch(InterruptedException | ExecutionException | TimeoutException e){  
    54.                     e.printStackTrace();  
    55.                 }finally{  
    56.                     server.accept(null,this);  
    57.                     try {  
    58.                         writeResult.get();  
    59.                         result.close();  
    60.                     } catch (InterruptedException | ExecutionException e) {  
    61.                         e.printStackTrace();  
    62.                     } catch (IOException e) {  
    63.                         e.printStackTrace();  
    64.                     }  
    65.                 }  
    66.                   
    67.             }  
    68.   
    69.             @Override  
    70.             public void failed(Throwable exc, Object attachment) {  
    71.                 System.out.println("failed:"+exc);  
    72.             }  
    73.               
    74.         });  
    75.     }  
    76.       
    77.     public static void main(String[] args) {  
    78.         new AIOEchoServer().start();  
    79.         while(true){  
    80.             try {  
    81.                 Thread.sleep(1000);  
    82.             } catch (InterruptedException e) {  
    83.                 e.printStackTrace();  
    84.             }  
    85.         }  
    86.     }  
    87.   
    88. }  


    客户端:

    [java] view plain copy
     
      1. import java.io.IOException;  
      2. import java.net.InetSocketAddress;  
      3. import java.nio.ByteBuffer;  
      4. import java.nio.channels.AsynchronousSocketChannel;  
      5. import java.nio.channels.CompletionHandler;  
      6.   
      7. public class AIOClient {  
      8.   
      9.     public static void main(String[] args) throws IOException {  
      10.           
      11.         final AsynchronousSocketChannel client = AsynchronousSocketChannel.open();  
      12.           
      13.         InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1",8001);  
      14.           
      15.         CompletionHandler<Void, ? super Object> handler = new CompletionHandler<Void,Object>(){  
      16.   
      17.             @Override  
      18.             public void completed(Void result, Object attachment) {  
      19.                 client.write(ByteBuffer.wrap("Hello".getBytes()),null,   
      20.                         new CompletionHandler<Integer,Object>(){  
      21.   
      22.                             @Override  
      23.                             public void completed(Integer result,  
      24.                                     Object attachment) {  
      25.                                 final ByteBuffer buffer = ByteBuffer.allocate(1024);  
      26.                                 client.read(buffer,buffer,new CompletionHandler<Integer,ByteBuffer>(){  
      27.   
      28.                                     @Override  
      29.                                     public void completed(Integer result,  
      30.                                             ByteBuffer attachment) {  
      31.                                         buffer.flip();  
      32.                                         System.out.println(new String(buffer.array()));  
      33.                                         try {  
      34.                                             client.close();  
      35.                                         } catch (IOException e) {  
      36.                                             e.printStackTrace();  
      37.                                         }  
      38.                                     }  
      39.   
      40.                                     @Override  
      41.                                     public void failed(Throwable exc,  
      42.                                             ByteBuffer attachment) {  
      43.                                     }  
      44.                                       
      45.                                 });  
      46.                             }  
      47.   
      48.                             @Override  
      49.                             public void failed(Throwable exc, Object attachment) {  
      50.                             }  
      51.                       
      52.                 });  
      53.             }  
      54.   
      55.             @Override  
      56.             public void failed(Throwable exc, Object attachment) {  
      57.             }  
      58.               
      59.         };  
      60.           
      61.         client.connect(serverAddress, null, handler);  
      62.         try {  
      63.             Thread.sleep(1000);  
      64.         } catch (InterruptedException e) {  
      65.             e.printStackTrace();  
      66.         }  
      67.     }  
      68.   
      69. }  
  • 相关阅读:
    微信带参数的小程序码生成并上传到七牛云(java)
    数据结构-数组和广义表-思维导图
    数据结构-串-思维导图
    数据结构-栈与队列-思维导图
    数据结构-线性表-思维导图
    python 拆分csv文件
    记录自己写js一个bug
    win10快捷键收藏
    重装系统win10最新版(完整版)
    formController的函数的基本作用
  • 原文地址:https://www.cnblogs.com/kexianting/p/8515043.html
Copyright © 2011-2022 走看看