ITeye博客

java nio异步读取 转载

chenpi529 · 2011-12-29 11:25 · java · 编程语言 · Markdown

网上有很多网友用很通俗的比喻 把同步和异步讲解的很透彻 转过来

举个例子:普通B/S模式(同步)AJAX技术(异步)
同步:提交请求->等待服务器处理->处理完毕返回 这个期间客户端浏览器不能干任何事
异步: 请求通过事件触发->服务器处理(这是浏览器仍然可以作其他事情)->处理完毕

同步就是你叫我去吃饭,我听到了就和你去吃饭;如果没有听到,你就不停的叫,直到我告诉你听到了,才一起去吃饭。
异步就是你叫我,然后自己去吃饭,我得到消息后可能立即走,也可能等到下班才去吃饭。
所以,要我请你吃饭就用同步的方法,要请我吃饭就用异步的方法,这样你可以省钱。

以通讯为例
同步:发送一个请求,等待返回,然后再发送下一个请求
异步:发送一个请求,不等待返回,随时可以再发送下一个请求
并发:同时发送多个请求

下面再转一段关于java异步应用的文章

    用异步输入输出流编写Socket进程通信程序

在Merlin中加入了用于实现异步输入输出机制的应用程序接口包:java.nio(新的输入输出包,定义了很多基本类型缓冲(Buffer)), java.nio.channels(通道及选择器等,用于异步输入输出),java.nio.charset(字符的编码解码)。通道 (Channel)首先在选择器(Selector)中注册自己感兴趣的事件,当相应的事件发生时,选择器便通过选择键(SelectionKey)通知已注册的通道。然后通道将需要处理的信息,通过缓冲(Buffer)打包,编码/解码,完成输入输出控制。

       通道介绍:

这里主要介绍ServerSocketChannel和 SocketChannel.它们都是可选择的(selectable)通道,分别可以工作在同步和异步两种方式下(注意,这里的可选择不是指可以选择两种工作方式,而是指可以有选择的注册自己感兴趣的事件)。可以用channel.configureBlocking(Boolean )来设置其工作方式。与以前版本的API相比较,ServerSocketChannel就相当于ServerSocket (ServerSocketChannel封装了ServerSocket),而SocketChannel就相当于Socket (SocketChannel封装了Socket)。当通道工作在同步方式时,编程方法与以前的基本相似,这里主要介绍异步工作方式。

所谓异步输入输出机制,是指在进行输入输出处理时,不必等到输入输出处理完毕才返回。所以异步的同义语是非阻塞(None Blocking)。在服务器端,ServerSocketChannel通过静态函数open()返回一个实例serverChl。然后该通道调用 serverChl.socket().bind()绑定到服务器某端口,并调用register(Selector sel, SelectionKey.OP_ACCEPT)注册OP_ACCEPT事件到一个选择器中(ServerSocketChannel只可以注册 OP_ACCEPT事件)。当有客户请求连接时,选择器就会通知该通道有客户连接请求,就可以进行相应的输入输出控制了;在客户端,clientChl实例注册自己感兴趣的事件后(可以是OP_CONNECT,OP_READ,OP_WRITE的组合),调用clientChl.connect (InetSocketAddress )连接服务器然后进行相应处理。注意,这里的连接是异步的,即会立即返回而继续执行后面的代码。

       选择器和选择键介绍:

选择器(Selector)的作用是:将通道感兴趣的事件放入队列中,而不是马上提交给应用程序,等已注册的通道自己来请求处理这些事件。换句话说,就是选择器将会随时报告已经准备好了的通道,而且是按照先进先出的顺序。那么,选择器是通过什么来报告的呢?选择键(SelectionKey)。选择键的作用就是表明哪个通道已经做好了准备,准备干什么。你也许马上会想到,那一定是已注册的通道感兴趣的事件。不错,例如对于服务器端serverChl来说,可以调用key.isAcceptable()来通知serverChl有客户端连接请求。相应的函数还有: SelectionKey.isReadable(),SelectionKey.isWritable()。一般的,在一个循环中轮询感兴趣的事件(具体可参照下面的代码)。如果选择器中尚无通道已注册事件发生,调用Selector.select()将阻塞,直到有事件发生为止。另外,可以调用 selectNow()或者select(long timeout)。前者立即返回,没有事件时返回0值;后者等待timeout时间后返回。一个选择器最多可以同时被63个通道一起注册使用。

        应用实例:

下面是用异步输入输出机制实现的客户/服务器实例程序�D�D程序清单1(限于篇幅,只给出了服务器端实现,读者可以参照着实现客户端代码):
  1.     public class NBlockingServer {
    
  2.         int port = 8000;
    
  3.         int BUFFERSIZE = 1024;
    
  4.         Selector selector = null;
    
  5.         ServerSocketChannel serverChannel = null;
    
  6.         HashMap clientChannelMap = null;//用来存放每一个客户连接对应的套接字和通道
    
  7.         public NBlockingServer( int port ) {
    
  8.             this.clientChannelMap = new HashMap();
    
  9.         this.port = port;
    
  10.     }
    
  11.     public void initialize() throws IOException {
    
  12.       //初始化,分别实例化一个选择器,一个服务器端可选择通道
    
  13.       this.selector = Selector.open();
    
  14.       this.serverChannel = ServerSocketChannel.open();
    
  15.       this.serverChannel.configureBlocking(false);
    
  16.       InetAddress localhost = InetAddress.getLocalHost();
    
  17.       InetSocketAddress isa = new InetSocketAddress(localhost, this.port );
    
  18.       this.serverChannel.socket().bind(isa);//将该套接字绑定到服务器某一可用端口
    
  19.     }
    
  20.     //结束时释放资源
    
  21.     public void finalize() throws IOException {
    
  22.         this.serverChannel.close();
    
  23.         this.selector.close();
    
  24.     }
    
  25.     //将读入字节缓冲的信息解码
    
  26.     public String decode( ByteBuffer byteBuffer ) throws 
    
  27. CharacterCodingException {
    
  28.         Charset charset = Charset.forName( "ISO-8859-1" );
    
  29.         CharsetDecoder decoder = charset.newDecoder();
    
  30.         CharBuffer charBuffer = decoder.decode( byteBuffer );
    
  31.         String result = charBuffer.toString();
    
  32.         return result;
    
  33.     }
    
  34.     //监听端口,当通道准备好时进行相应操作
    
  35.     public void portListening() throws IOException, InterruptedException {
    
  36.       //服务器端通道注册OP_ACCEPT事件
    
  37.       SelectionKey acceptKey =this.serverChannel.register( this.selector,
    
  38.                                            SelectionKey.OP_ACCEPT );
    
  39.         //当有已注册的事件发生时,select()返回值将大于0
    
  40.         while (acceptKey.selector().select() > 0 ) {
    
  41.             System.out.println("event happened");
    
  42.             //取得所有已经准备好的所有选择键
    
  43.             Set readyKeys = this.selector.selectedKeys();
    
  44.             //使用迭代器对选择键进行轮询
    
  45.             Iterator i = readyKeys.iterator();
    
  46.             while (i.hasNext()) {
    
  47.                 SelectionKey key = (SelectionKey)i.next();
    
  48.                 i.remove();//删除当前将要处理的选择键
    
  49.                 if ( key.isAcceptable() ) {//如果是有客户端连接请求
    
  50.                     System.out.println("more client connect in!");
    
  51.                     ServerSocketChannel nextReady =
    
  52.                         (ServerSocketChannel)key.channel();
    
  53.                     //获取客户端套接字
    
  54.                     Socket s = nextReady.accept();
    
  55.                     //设置对应的通道为异步方式并注册感兴趣事件
    
  56.                     s.getChannel().configureBlocking( false );
    
  57.                     SelectionKey readWriteKey =
    
  58.                         s.getChannel().register( this.selector,
    
  59.                             SelectionKey.OP_READ|SelectionKey.OP_WRITE  );
    
  60.                     //将注册的事件与该套接字联系起来
    
  61. readWriteKey.attach( s );
    
  62. //将当前建立连接的客户端套接字及对应的通道存放在哈希表//clientChannelMap中
    
  63.                     this.clientChannelMap.put( s, new 
    
  64. ClientChInstance( s.getChannel() ) );
    
  65.                     }
    
  66.                 else if ( key.isReadable() ) {//如果是通道读准备好事件
    
  67.                     System.out.println("Readable");
    
  68.                     //取得选择键对应的通道和套接字
    
  69.                     SelectableChannel nextReady =
    
  70.                         (SelectableChannel) key.channel();
    
  71.                     Socket socket = (Socket) key.attachment();
    
  72.                     //处理该事件,处理方法已封装在类ClientChInstance中
    
  73.                     this.readFromChannel( socket.getChannel(),
    
  74.                     (ClientChInstance)
    
  75. this.clientChannelMap.get( socket ) );
    
  76.                 }
    
  77.                 else if ( key.isWritable() ) {//如果是通道写准备好事件
    
  78.                     System.out.println("writeable");
    
  79.                     //取得套接字后处理,方法同上
    
  80.                     Socket socket = (Socket) key.attachment();
    
  81.                     SocketChannel channel = (SocketChannel) 
    
  82. socket.getChannel();
    
  83.                     this.writeToChannel( channel,"This is from server!");
    
  84.                 }
    
  85.             }
    
  86.         }
    
  87.     }
    
  88.     //对通道的写操作
    
  89.     public void writeToChannel( SocketChannel channel, String message ) 
    
  90. throws IOException {
    
  91.         ByteBuffer buf = ByteBuffer.wrap( message.getBytes()  );
    
  92.         int nbytes = channel.write( buf );
    
  93.     }
    
  94.      //对通道的读操作
    
  95.     public void readFromChannel( SocketChannel channel, ClientChInstance clientInstance )
    
  96.     throws IOException, InterruptedException {
    
  97.         ByteBuffer byteBuffer = ByteBuffer.allocate( BUFFERSIZE );
    
  98.     int nbytes = channel.read( byteBuffer );
    
  99.     byteBuffer.flip();
    
  100.     String result = this.decode( byteBuffer );
    
  101.     //当客户端发出”@exit”退出命令时,关闭其通道
    
  102.     if ( result.indexOf( "@exit" ) >= 0 ) {
    
  103.         channel.close();
    
  104.     }
    
  105.     else {
    
  106.             clientInstance.append( result.toString() );
    
  107.             //读入一行完毕,执行相应操作
    
  108.             if ( result.indexOf( ""n" ) >= 0 ){
    
  109.             System.out.println("client input"+result);
    
  110.             clientInstance.execute();
    
  111.             }
    
  112.     }
    
  113. }
    
  114. //该类封装了怎样对客户端的通道进行操作,具体实现可以通过重载execute()方法
    
  115. public class ClientChInstance {
    
  116.     SocketChannel channel;
    
  117.     StringBuffer buffer=new StringBuffer();
    
  118.     public ClientChInstance( SocketChannel channel ) {
    
  119.         this.channel = channel;
    
  120.     }
    
  121.     public void execute() throws IOException {
    
  122.         String message = "This is response after reading from channel!";
    
  123.         writeToChannel( this.channel, message );
    
  124.         buffer = new StringBuffer();
    
  125.     }
    
  126.     //当一行没有结束时,将当前字窜置于缓冲尾
    
  127.     public void append( String values ) {
    
  128.         buffer.append( values );
    
  129.     }
    
  130. }
    
  131. //主程序
    
  132. public static void main( String args ) {
    
  133.     NBlockingServer nbServer = new NBlockingServer(8000);
    
  134.     try {
    
  135.         nbServer.initialize();
    
  136.     } catch ( Exception e ) {
    
  137.         e.printStackTrace();
    
  138.         System.exit( -1 );
    
  139.     }
    
  140.     try {
    
  141.         nbServer.portListening();
    
  142.     }
    
  143.     catch ( Exception e ) {
    
  144.         e.printStackTrace();
    
  145.     }
    
  146. }
    
  147. }

小结:

从以上程序段可以看出,服务器端没有引入多余线程就完成了多客户的客户/服务器模式。该程序中使用了回调模式(CALLBACK),细心的读者应该早就看出来了。需要注意的是,请不要将原来的输入输出包与新加入的输入输出包混用,因为出于一些原因的考虑,这两个包并不兼容。即使用通道时请使用缓冲完成输入输出控制。该程序在Windows2000,J2SE1.4下,用telnet测试成功

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。