JAVA NIO之个人理解

最近在一个项目中用到了Java的NIO,因为之前一直没有真正的在项目中用过NIO,所以对NIO一直都不是很了解。
这次在项目的压迫下,终于对NIO有了一个简单的了解。在这里把我的理解写出来,希望对大家有所帮助。

首先介绍一下,什么是NIO。

从JDK 1.4开始,Java的标准库中就包含了NIO,即所谓的“New IO”。其中最重要的功能就是提供了“非阻塞”的IO,当然包括了Socket。NonBlocking的IO就是对select(Unix平台下)以及 WaitForMultipleObjects(Windows平台)的封装,提供了高性能、易伸缩的服务架构。
传统的Server/Client实现是基于Thread per request,即服务器为每个客户端请求建立一个线程处理,单独负责处理一个客户的请求。比如像Tomcat(新版本也会提供NIO方案)、Resin等Web服务器就是这样实现的。当然为了减少瞬间峰值问题,服务器一般都使用线程池,规定了同时并发的最大数量,避免了线程的无限增长。

但这样有一个问题:如果线程池的大小为100,当有100个用户同时通过HTTP现在一个大文件时,服务器的线程池会用完,因为所有的线程都在传输大文件了,即使第101个请求者仅仅请求一个只有10字节的页面,服务器也无法响应了,只有等到线程池中有空闲的线程出现。

另外,线程的开销也是很大的,特别是达到了一个临界值后,性能会显著下降,这也限制了传统的Socket方案无法应对并发量大的场合,而“非阻塞”的IO就能轻松解决这个问题。

NIO服务器最核心的一点就是反应器模式:当有感兴趣的事件发生的,就通知对应的事件处理器去处理这个事件,如果没有,则不处理。所以使用一个线程做轮询就可以了。当然这里这是个例子,如果要获得更高性能,可以使用少量的线程,一个负责接收请求,其他的负责处理请求,特别是对于多CPU时效率会更高。

(上面这段NIO的介绍引自http://www.javaeye.com/topic/40489,因为觉得说的很明白,我就懒得再总结了,直接拷贝)

在我们平时使用NIO的时候,最常用到的就是下面这几个类:
  java.nio.channels.SelectionKey;
  java.nio.channels.Selector;
  java.nio.channels.ServerSocketChannel;
  java.nio.channels.SocketChannel;

其中最为重要的就是Selector类。Selector类通过调用select方法,将注册的channel中有事件发生的取出来进行处理。
因此,我们如果想要把管理权交到Selector类手中,首先就先要在Selector对象中注册相应的Chanel。
这里我们看到了2种不同的Channel:ServerSocketChannel 和 SocketChannel。

ServerSocketChannel主要用在Server中,用于接收客户端的链接请求
SocketChannel则用于真正的读写数据,同时还可以用于客户端发送链接请求。

当我们要开发一个服务器端程序时,首先我们需要创建一个ServerSocketChannel,并将其注册到selector当中。
   ServerSocketChannel server = ServerSocketChannel.open();   // 获取ServerSocketChannel
   Selector sel = Selector.open();                                                  // 获取Selector
   server.socket().bind(new InetSocketAddress(port));                // 将ServerSocketChannel绑定到本机具体端口上
   server.configureBlocking(false);                                                // 设置ServerSocketChannel为非阻塞模式
   server.register(sel, SelectionKey.OP_ACCEPT);                        // 将ServerSocketChannel注册到Selector中,关注的事件是OP_ACCEPT
   
在我们把ServerSocketChannel注册到Selector之后,
当有客户端向该Server所在的IP地址和端口发送连接socket请求时,Selector就会捕捉到这个事件,并进行相应的出来。
   int n = selector.select();                                   // 得到selector所捕获的事件数量
   if( n > 0 ){                                                        // 当真正捕获到事件时,才执行相应操作
    Set selectedKeys = selector.selectedKeys();  // 获取捕获到的事件集合
    Iterator i = selectedKeys.iterator();
    while(i.hasNext())              
    {
       SelectionKey s = (SelectionKey) i.next(); // 对事件一一处理

       //一个key被处理完成后,就都被从就绪关键字(ready keys)列表中除去
       i.remove();
       if(s.isAcceptable())                                   // 表示该事件为OP_ACCEPT事件
       {
         // 从channel()中取得我们刚刚注册的ServerSocketChannel。
         // 为请求获取新的SocketChannel
         SocketChannel sc = ((ServerSocketChannel)s.channel()).accept().socket().getChannel(); 

         sc.configureBlocking(false);                 // 设置SocketChannel为非阻塞方式
         sc.register(selector, SelectionKey.OP_READ |SelectionKey.OP_WRITE); 
                       // 将新的SocketChannel注册到selector中,注册事件为OP_READ和OP_WRITE
       }
       else
       {
         // 执行其他操作
       }
     }
   }

从上面的程序中,我们可以看出,当有新的连接请求到达时,会获取到新的连接所对应的SocketChannel,并将其注册到selector当中。
其实真正实现读写数据操作的就是这些SocketChannel,上面的ServerSocketChannel只是负责接收连接请求。
当有数据需要接收处理时,selector同样会获取到相应的事件,并进行相应的处理。

       SelectionKey s = (SelectionKey) i.next();                          // 对事件一一处理

       //一个key被处理完成后,就都被从就绪关键字(ready keys)列表中除去
       i.remove();
                  ByteBuffer clientBuffer = ByteBuffer.allocate(4096);
       if (key.isReadable()) {                                                               // 读信息
                     SocketChannel channel = (SocketChannel) key.channel();    // 获取相应的SocketChannel
                     int count = channel.read(clientBuffer);                                   // 将数据读入clientBuffer
                     if (count > 0) {                                                                       // 当有数据读入时
                         clientBuffer.flip();                                                               // 反转此缓冲区
                         CharBuffer charBuffer = decoder.decode(clientBuffer);     // 如果需要,对缓冲区中的字符进行解码
                          ...                                                                                     // 处理数据
                     }
                 }


其实,selector还可以监听写数据的事件SelectionKey.OP_WRITE,不过我觉得其中这么做是没有必要的。
因为当我们要向外写数据的时候,完全没有必要再将其交给selector,由selector来负责,我们直接通过SocketChannel写数据就好了。
所以这里就对写数据不多写了。

上面写的整个流程都是从服务器的角度来看的,下面我们再来看看客户端怎么做:

  InetSocketAddress addr = new InetSocketAddress(host,port);
   //生成一个socketchannel
   sc = SocketChannel.open();        
   //连接到server
   sc.connect(addr);                       // 连接到server

   if(sc.finishConnect()){                // 当连接成功时,执行相应操作
    ByteBuffer buffer = .....             // 准备数据
    
    buffer.filp();                              // 反转此缓冲区
    while(w_buff.hasRemaining())  // 发送数据到server
     sc.write(w_buff);
        
   }

客户端的实现非常简单,创建一个SocketChannel,并通过该SocketChannel尝试连接server,
当连接成功之后,就可以直接通过该SocketChannel向server发送数据了。
如果客户端需要读取来自服务器的数据,也可以直接通过SocketChannel调用read方法来读取数据并进行操作。

看过上面的东东,相信大家对于怎么使用NIO已经有了初步的了解。
我在网上找了一个我个人觉得还不错的例子,列在下面,供大家参考。
------------------------------------------------------------------
引自http://www.javaeye.com/topic/40489
      
      package nio.file;
           
            import java.io.FileInputStream;
            import java.io.IOException;
            import java.net.InetSocketAddress;
            import java.nio.ByteBuffer;
            import java.nio.CharBuffer;
            import java.nio.channels.FileChannel;
            import java.nio.channels.SelectionKey;
            import java.nio.channels.Selector;
            import java.nio.channels.ServerSocketChannel;
            import java.nio.channels.SocketChannel;
            import java.nio.charset.Charset;
            import java.nio.charset.CharsetDecoder;
            import java.util.Iterator;
           
            /**
             * 测试文件下载的NIOServer
             *
             * @author tenyears.cn
             */
            public class NIOServer {
              static int BLOCK = 4096;
              // 处理与客户端的交互
              public class HandleClient {
                protected FileChannel channel;
                protected ByteBuffer buffer;
                public HandleClient() throws IOException {
                  this.channel = new FileInputStream(filename).getChannel();
                  this.buffer = ByteBuffer.allocate(BLOCK);
                }
                public ByteBuffer readBlock() {
                  try {
                    buffer.clear();
                    int count = channel.read(buffer);
                    buffer.flip();
                    if (count <= 0)
                      return null;
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                  return buffer;
                }
                public void close() {
                  try {
                    channel.close();
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }
              }
           
              protected Selector selector;
              protected String filename = "d://bigfile.dat"; // a big file
              protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
              protected CharsetDecoder decoder;
           
              public NIOServer(int port) throws IOException {
                selector = this.getSelector(port);
                Charset charset = Charset.forName("GB2312");
                decoder = charset.newDecoder();
              }
           
              // 获取Selector
              protected Selector getSelector(int port) throws IOException {
                ServerSocketChannel server = ServerSocketChannel.open();
                Selector sel = Selector.open();
                server.socket().bind(new InetSocketAddress(port));
                server.configureBlocking(false);
                server.register(sel, SelectionKey.OP_ACCEPT);
                return sel;
              }
           
              // 监听端口
              public void listen() {
                try {
                  for (;;) {
                    selector.select();
                    Iterator<selectionkey></selectionkey> iter = selector.selectedKeys()
                        .iterator();
                    while (iter.hasNext()) {
                      SelectionKey key = iter.next();
                      iter.remove();
                      handleKey(key);
                    }
                  }
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
           
              // 处理事件
              protected void handleKey(SelectionKey key) throws IOException {
                if (key.isAcceptable()) { // 接收请求
                  ServerSocketChannel server = (ServerSocketChannel) key.channel();
                  SocketChannel channel = server.accept();
                  channel.configureBlocking(false);
                  channel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) { // 读信息
                  SocketChannel channel = (SocketChannel) key.channel();
                  int count = channel.read(clientBuffer);
                  if (count > 0) {
                    clientBuffer.flip();
                    CharBuffer charBuffer = decoder.decode(clientBuffer);
                    System.out.println("Client >>" + charBuffer.toString());
                    SelectionKey wKey = channel.register(selector,
                        SelectionKey.OP_WRITE);
                    wKey.attach(new HandleClient());
                  } else
                    channel.close();
                  clientBuffer.clear();
                } else if (key.isWritable()) { // 写事件
                  SocketChannel channel = (SocketChannel) key.channel();
                  HandleClient handle = (HandleClient) key.attachment();
                  ByteBuffer block = handle.readBlock();
                  if (block != null)
                    channel.write(block);
                  else {
                    handle.close();
                    channel.close();
                  }
                }
              }
           
              public static void main(String[] args) {
                int port = 12345;
                try {
                  NIOServer server = new NIOServer(port);
                  System.out.println("Listernint on " + port);
                  while (true) {
                    server.listen();
                  }
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            } 

该代码中,通过一个HandleClient来获取文件的一块数据,每一个客户都会分配一个HandleClient的实例。

下面是客户端请求的代码,也比较简单,模拟100个用户同时下载文件。

package nio.file;
            import java.io.IOException;
            import java.net.InetSocketAddress;
            import java.nio.ByteBuffer;
            import java.nio.CharBuffer;
            import java.nio.channels.SelectionKey;
            import java.nio.channels.Selector;
            import java.nio.channels.SocketChannel;
            import java.nio.charset.Charset;
            import java.nio.charset.CharsetEncoder;
            import java.util.Iterator;
            import java.util.concurrent.ExecutorService;
            import java.util.concurrent.Executors;
           
            /**
             * 文件下载客户端
             * @author tenyears.cn
             */
            public class NIOClient {
              static int SIZE = 100;
              static InetSocketAddress ip = new InetSocketAddress("localhost",12345);
              static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
              static class Download implements Runnable {
                protected int index;
                public Download(int index) {
                  this.index = index;
                }
           
                public void run() {
                  try {
                    long start = System.currentTimeMillis();
                    SocketChannel client = SocketChannel.open();
                    client.configureBlocking(false);
                    Selector selector = Selector.open();
                    client.register(selector, SelectionKey.OP_CONNECT);
                    client.connect(ip);
                    ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
                    int total = 0;
                    FOR: for (;;) {
                      selector.select();
                      Iterator<selectionkey></selectionkey> iter = selector.selectedKeys()
                          .iterator();
                      while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isConnectable()) {
                          SocketChannel channel = (SocketChannel) key
                              .channel();
                          if (channel.isConnectionPending())
                            channel.finishConnect();
                          channel.write(encoder.encode(CharBuffer
                              .wrap("Hello from " + index)));
                          channel.register(selector, SelectionKey.OP_READ);
                        } else if (key.isReadable()) {
                          SocketChannel channel = (SocketChannel) key
                              .channel();
                          int count = channel.read(buffer);
                          if (count > 0) {
                            total += count;
                            buffer.clear();
                          } else {
                            client.close();
                            break FOR;
                          }
                        }
                      }
                    }
                    double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
                    System.out.println("Thread " + index + " downloaded " + total
                        + "bytes in " + last + "s.");
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }
              }
           
              public static void main(String[] args) throws IOException {
                ExecutorService exec = Executors.newFixedThreadPool(SIZE);
                for (int index = 0; index < SIZE; index++) {
                  exec.execute(new Download(index));
                }
                exec.shutdown();
              }
            }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值