JDK7网络异步IO

来源:互联网 发布:通达信量比公式源码 编辑:程序博客网 时间:2024/05/20 06:09


在Reactor模式中,虽然可以采用non-blocking I/O模式,使用Selector注册感兴趣的I/O事件和读取感兴趣的I/O事件,I/O调用者向I/O系统请求一个I/O调用时,I/O立即返回给调用者一个反馈,这些反馈无外乎两大类型,请求已经被执行并且有结果返回,或者当前的通道缓存中无数据可用。第二种情况下,为保险起见,编写程序时需要写一个循环只到有数据被读取为止。在I/O系统处理一个I/O请求时,不可能同时处理第二个I/O操作。

 

异步I/O与同步I/O的最大不同是:当调用者向异步I/O系统请求一个I/O操作的时候,I/O系统自身会调用系统资源启动一个线程去处理该请求,当这个请求被处理完成后,通知调用者,并返回结果给调用者。在这个过程之中,调用者在自身的线程中可以去干一些别的工作。这种I/O处理方式提高了应用程序的可扩展性和性能。

 

JDK7中的NIO2版本引入了异步IO的功能。支持文件异步I/O操作和网络异步I/O操作。针对于网络部分的主要3个类和一个接口。

 

主要的类

1,  AsynchronousChannelGroup,这个类与一组AsynchronousSocketChannel相关联,并且与I/O系统交互,当有I/O请求被处理完成后,会把处理结果通知给一个实现了CompletionHandler接口的对象派发给相关的AsynchronousSocketChannel. 这个类在在使用时需要制定一个ExecutorService对象,ExecutorService对象中的线程池是用来应对与I/O系统交互及与通知调用者时需要的线程开销。

 

2, AsynchronousServerSocketChannel,异步网络ServerSocket,主要用来绑定端口,并接受客户端的连接。accept可以返回一个Future<AsynchronousSocketChannel>对象,调用Future对象的get方法得到一个传入的套接字 的通道对象,如

Java代码  收藏代码
  1. AsynchronousServerSocketChannel listener = .....  
  2. listener.bind(new InetSocketAddress(9001));  
  3. Future<AsynchronousSocketChannel> future = listener.accept();  
  4. AsynchronousSocketChannel channel = future.get();  
  5. ..  

在Future对象中拿到传入的套接字通道对象后,才可以再次调用accept方法拿到新的套接字通道,否则会抛出AcceptPendingException,虽然是异步的,不过这个方法实质上类似于同步的。

 

另外一种拿到套接字通道对象的方法是使用CompletionHandler的回调方式。这种方式也是Sun鼓励的方式。一旦套接字通道建立完成,I/O系统会调用CompletionHandler对象的completed方法,把已经建立连接的套接字通道传入到completed方法的第一参数当中去。 这个通道建立后,可以让服务器AsynchronousServerSocketChannel对象再次接受新的套接字通道。接着可以用这个刚刚建立的套接字通道来进行数据通讯的工作。

Java代码  收藏代码
  1. listener.accept(nullnew CompletionHandler<AsynchronousSocketChannel,Void>() {  
  2.       public void completed(AsynchronousSocketChannel ch, Void att) {  
  3.           // accept the next connection  
  4.           listener.accept(nullthis);  
  5.   
  6.           // handle this connection  
  7.           ....  
  8.           .....  
  9.       }  
  10.       public void failed(Throwable exc, Void att) {  
  11.           ...  
  12.       }  
  13.   });  
 

 

3, AsynchronousSocketChannel,真正的数据通讯类,使用write方法向channel的缓冲中写入数据,使用read方法读取channel缓冲中的数据,读和写的I/O操作完成后,I/O系统会发出一个通知,把读取、写入的字节数传入到CompletionHandler<Integer, A>对象中的completed方法的第一个参数。与AsynchronousServerSocketChannel的accept方法类型,如果一个I/O操作完成,而另外一个I/O操作又发起的话,会抛出PendingReadException或者PendingWriteException.因此在用AsynchronousSocketChannel处理I/O操作时,要非常小心,确保一个I/O操作发起前,要确保这个通道上的上一个I/O操作已经完成。

 

 

4, CompletionHandler接口,实现这个接口的对象在异步I/O操作中承担着通知的作用,当操作完成后,I/O系统会把通知的内容发送到completed方法中的第一个参数,并且I/O系统会调用completed方法。CompletionHandler按照使用场合可以分成3种:

AsynchronousServerSocket类中中用于接受传入连接套接字通道后的接入套接字通道完成通知,采用泛形声明的方式

Java代码  收藏代码
  1. CompletionHandler<AsynchronousSocketChannel, A>  
 

AsynchronousSocketChannel写数据后的写入完成通知

Java代码  收藏代码
  1. CompletionHandler<Integer, A>  
 

AsynchronousSocketChannel读取数据后的读取完成通知,如写入通知的声明相同。

 

异步读和写的问题

使用通道来读取数据时,首先是从通道的缓冲区读取一定量的数据到ByteBuffer中目标缓存中,如果目标缓存没有剩余的字节可供写入,直接返回零给读取通知的completed方法的第一个参数,如果这个参数的值为-1,表示缓冲区中没有可供读取的字节或者当前通道中的套接字输入流已经关闭。因为读写都是异步的,所以一端的通道进行I/O操作后如果立即关闭,另外一个端的通道很有可能仍然处于相对应的I/O操作过程之中,这样的情形下,会抛出一个远程通道被强制关闭的IOException。因此,在通道接收数据时,需要根据completed方法的第一个参数来判断是否需要关闭当前的通道,如果不能及时关闭通道,容易引起内存泄露的问题。

 

I/O系统何时把通道缓冲区中的字节传输到远程通道中的缓冲区里,这个是由I/O系统决定,而对于异步I/O的开发人员来说,是不可控制的,假如代码在客户端向通道里写入了3个字节序列,这3个序列在远程的接收端通道里可能会被接收成3个同样的字节序列,也有可能是2个序列,也有可能是1个序列,但是不伦是接受到几个序列,这些接受到的序列的内容和发送序列的内容是一样的。

 

无论读和写,都是不是线程安全的,必须等到I/O系统通知调用者后,才可以进行下一个操作,这个在多线程环境下,需要格外小心。

 

异步Echo Server

Java代码  收藏代码
  1. public class AsynEchoServer {  
  2.   
  3.     private int port = 9999;  
  4.   
  5.     private int backlog = 50;  
  6.   
  7.     private int threadPoolSize = 20;  
  8.   
  9.     private int initialSize = 5;  
  10.   
  11.     public void start() throws IOException {  
  12.         ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);  
  13.         AsynchronousChannelGroup group = AsynchronousChannelGroup.withCachedThreadPool(executor, initialSize);  
  14.         AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open(group);  
  15.         listener.bind(new InetSocketAddress(port), backlog);  
  16.         listener.accept(listener, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {  
  17.   
  18.             @Override  
  19.             public void completed(AsynchronousSocketChannel channel, AsynchronousServerSocketChannel listener) {  
  20.                 listener.accept(listener, this);  
  21.                 ByteBuffer buffer = ByteBuffer.allocate(512);  
  22.                 channel.read(buffer, buffer, new EchoHandler(channel, buffer));  
  23.             }  
  24.   
  25.             @Override  
  26.             public void failed(Throwable exc, AsynchronousServerSocketChannel listener) {  
  27.                 exc.printStackTrace();  
  28.                 try {  
  29.                     listener.close();  
  30.                 } catch (IOException e) {  
  31.                     e.printStackTrace();  
  32.                 } finally {  
  33.                     System.exit(-1);  
  34.                 }  
  35.             }  
  36.         });  
  37.     }  
  38.   
  39.     /** 
  40.      * @param args 
  41.      * @throws IOException 
  42.      */  
  43.     public static void main(String[] args) throws IOException {  
  44.         AsynEchoServer server = new AsynEchoServer();  
  45.         server.start();  
  46.     }  
  47.   
  48.     // getter & setters  
  49. }  
 
Java代码  收藏代码
  1. class EchoHandler implements CompletionHandler<Integer, ByteBuffer> {  
  2.     private static Charset utf8 = Charset.forName("utf-8");  
  3.     AsynchronousSocketChannel channel;  
  4.     ByteBuffer buffer;  
  5.   
  6.     public EchoHandler(AsynchronousSocketChannel channel, ByteBuffer buffer) {  
  7.         this.channel = channel;  
  8.         this.buffer = buffer;  
  9.     }  
  10.   
  11.     @Override  
  12.     public void completed(Integer result, ByteBuffer buff) {  
  13.         if (result == -1) {  
  14.             try {  
  15.                 channel.close();  
  16.             } catch (IOException e) {  
  17.                 e.printStackTrace();  
  18.             }  
  19.         } else if (result > 0) {  
  20.             buffer.flip();  
  21.             String msg = utf8.decode(buffer).toString();  
  22.             System.out.println("echo: " + msg);  
  23.             Future<Integer> w = channel.write(utf8.encode(msg));  
  24.             try {  
  25.                 w.get();  
  26.             } catch (InterruptedException e) {  
  27.                 e.printStackTrace();  
  28.             } catch (ExecutionException e) {  
  29.                 e.printStackTrace();  
  30.             }  
  31.               
  32.             buffer.clear();  
  33.             channel.read(buff, buff, this);  
  34.         }  
  35.     }  
  36.   
  37.     @Override  
  38.     public void failed(Throwable exc, ByteBuffer buff) {  
  39.         // TODO Auto-generated method stub  
  40.     }  
  41. }  

 

EchoClient

Java代码  收藏代码
  1. class EchoClient {  
  2.     private static Charset utf8 = Charset.forName("utf-8");  
  3.     private int port = 9999;  
  4.     private String remoteHost;  
  5.     private String[] message;  
  6.     private AsynchronousSocketChannel channel;  
  7.   
  8.     public static void main(String args[]) throws Exception {  
  9.         if (args.length >= 2) {  
  10.             String msgs[] = new String[args.length - 1];  
  11.             System.arraycopy(args, 1, msgs, 0, msgs.length);  
  12.             EchoClient client = new EchoClient(args[0], msgs);  
  13.             client.connect();  
  14.             client.sendAndReceive();  
  15.             Thread.sleep(3000);  
  16.             client.close();  
  17.             Thread.sleep(3000);  
  18.         } else {  
  19.             System.out.println("usage EchoClient [remotehost] [messages .... ]");  
  20.         }  
  21.     }  
  22.   
  23.     public void sendAndReceive() throws InterruptedException, ExecutionException {  
  24.         ByteBuffer buffer = ByteBuffer.allocate(512);  
  25.         for (String msg : this.message) {  
  26.             Future<Integer> w = channel.write(utf8.encode(msg));  
  27.             w.get();  
  28.         }  
  29.           
  30.         channel.read(buffer, buffer, new ReceiverHandler(channel, buffer));  
  31.     }  
  32.   
  33.     public void close() throws IOException {  
  34.         channel.shutdownInput();  
  35.         channel.shutdownOutput();  
  36.     }  
  37.   
  38.     public EchoClient(String remoteHost, String[] message) {  
  39.         super();  
  40.         this.remoteHost = remoteHost;  
  41.         this.message = message;  
  42.     }  
  43.   
  44.     public void connect() throws IOException, InterruptedException, ExecutionException {  
  45.         channel = AsynchronousSocketChannel.open();  
  46.         Future<Void> r = channel.connect(new InetSocketAddress(this.remoteHost, this.port));  
  47.         r.get();  
  48.     }  
  49.   
  50.     //  getter & setters  
  51. }  

 

Java代码  收藏代码
  1. class ReceiverHandler implements CompletionHandler<Integer, ByteBuffer> {  
  2.     private static Charset utf8 = Charset.forName("utf-8");  
  3.     private AsynchronousSocketChannel channel;  
  4.     private ByteBuffer buffer;  
  5.   
  6.     @Override  
  7.     public void completed(Integer result, ByteBuffer buff) {  
  8.           
  9.         if (result > 0) {              
  10.             buffer.flip();  
  11.             System.out.println(utf8.decode(buffer));  
  12.             buffer.clear();  
  13.             channel.read(buff, buff, this);  
  14.         }else if (result==-1){  
  15.             try {  
  16.                 channel.close();  
  17.             } catch (IOException e) {  
  18.                 e.printStackTrace();  
  19.             }  
  20.         }  
  21.     }  
  22.   
  23.     @Override  
  24.     public void failed(Throwable exc, ByteBuffer buff) {  
  25.         exc.printStackTrace();  
  26.     }  
  27.   
  28.     public ReceiverHandler(AsynchronousSocketChannel channel, ByteBuffer buffer) {  
  29.         super();  
  30.         this.channel = channel;  
  31.         this.buffer = buffer;  
  32.     }  
  33. }  
0 0