java AIO示例

BIO:同步阻塞IO操作、NIO:同步非阻塞IO操作、AIO:异步非阻塞IO操作。

NIO通过监听请求,处理请求,之后返回结果,属于同步操作。AIO监听请求,后台应用程序处理请求(这个时候监听器继续监听请求),回调结果。后端的应用只是处理等待队列中的请求,这样请求处理和执行任务就分离了,实现异步操作。

AIO是异步IO的缩写,虽然NIO在网络操作中,提供了非阻塞的方法,但是NIO的IO行为还是同步的。对于NIO来说,我们的业务线程是在IO操作准备好时,得到通知,接着就由这个线程自行进行IO操作,IO操作本身是同步的。

但是对AIO来说,则更加进了一步,它不是在IO准备好时再通知线程,而是在IO操作已经完成后,再给线程发出通知。因此AIO是不会阻塞的,此时我们的业务逻辑将变成一个回调函数,等待IO操作完成后,由系统自动触发。

下面的程序是通过AIO来实现一个简单的EchoServer以及对应的客户端。

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

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

   void completed(Vresult, Aattachment);

   void failed(Throwableexc, Aattachment);


说了这么多,感觉很像 Ajax中的回调方法,只不过换成了类。直接看代码吧:

服务端:

  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. }  
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AIOEchoServer {

	public final static int PORT = 8001;
	public final static String IP = "127.0.0.1";

	
	private AsynchronousServerSocketChannel server = null;
	
	public AIOEchoServer(){
		try {
			//同样是利用工厂方法产生一个通道,异步通道 AsynchronousServerSocketChannel
			server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(IP,PORT));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//使用这个通道(server)来进行客户端的接收和处理
	public void start(){
		System.out.println("Server listen on "+PORT);
		
		//注册事件和事件完成后的处理器,这个CompletionHandler就是事件完成后的处理器
		server.accept(null,new CompletionHandler<AsynchronousSocketChannel,Object>(){

			final ByteBuffer buffer = ByteBuffer.allocate(1024);
			
			@Override
			public void completed(AsynchronousSocketChannel result,Object attachment) {
				
				System.out.println(Thread.currentThread().getName());
				Future<Integer> writeResult = null;
				
				try{
					buffer.clear();
					result.read(buffer).get(100,TimeUnit.SECONDS);
					
					System.out.println("In server: "+ new String(buffer.array()));
					
					//将数据写回客户端
					buffer.flip();
					writeResult = result.write(buffer);
				}catch(InterruptedException | ExecutionException | TimeoutException e){
					e.printStackTrace();
				}finally{
					server.accept(null,this);
					try {
						writeResult.get();
						result.close();
					} catch (InterruptedException | ExecutionException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}

			@Override
			public void failed(Throwable exc, Object attachment) {
				System.out.println("failed:"+exc);
			}
			
		});
	}
	
	public static void main(String[] args) {
		new AIOEchoServer().start();
		while(true){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

客户端:

  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. }  
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AIOClient {

	public static void main(String[] args) throws IOException {
		
		final AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
		
		InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1",8001);
		
		CompletionHandler<Void, ? super Object> handler = new CompletionHandler<Void,Object>(){

			@Override
			public void completed(Void result, Object attachment) {
				client.write(ByteBuffer.wrap("Hello".getBytes()),null, 
						new CompletionHandler<Integer,Object>(){

							@Override
							public void completed(Integer result,
									Object attachment) {
								final ByteBuffer buffer = ByteBuffer.allocate(1024);
								client.read(buffer,buffer,new CompletionHandler<Integer,ByteBuffer>(){

									@Override
									public void completed(Integer result,
											ByteBuffer attachment) {
										buffer.flip();
										System.out.println(new String(buffer.array()));
										try {
											client.close();
										} catch (IOException e) {
											e.printStackTrace();
										}
									}

									@Override
									public void failed(Throwable exc,
											ByteBuffer attachment) {
									}
									
								});
							}

							@Override
							public void failed(Throwable exc, Object attachment) {
							}
					
				});
			}

			@Override
			public void failed(Throwable exc, Object attachment) {
			}
			
		};
		
		client.connect(serverAddress, null, handler);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值