paulwong

          NIO概念

          NIO是新IO,與老IO相比,老IO是通過STREAM來發送CHARACTER,新IO是通過CHANNL 發送BUFFER;老IO對于多條鏈接需要啟動多個線程處理,新IO只需一條線程即可處理多條鏈接;新IO是事件驅動。


          客戶端,非SELECTOR模式:
          //打開一個CHANNEL
          SocketChannel socketChannel = SocketChannel.open();
          socketChannel.configureBlocking(false);
          socketChannel.connect(new InetSocketAddress("http://google.com", 80));

          //等待可寫狀態
          while(! socketChannel.finishConnect() ){
              //wait, or do something else    
          }

          //寫資料
          socketChannel.write(buf);


          客戶端,SELECTOR模式:
          //打開一個CHANNEL
          SocketChannel channel = SocketChannel.open();

          //新建一個SELECTOR
          Selector selector = Selector.open();

          channel.configureBlocking(false);

          //將SELECTOR注冊到CHANNEL中
          SelectionKey key = channel.register(selector, SelectionKey.OP_READ);


          while(true) {

            //查詢可用狀態
            int readyChannels = selector.select();

            //狀態不可用
            if(readyChannels == 0) continue;

          }

            //狀態可用
            Set<SelectionKey> selectedKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while(keyIterator.hasNext()) {

              SelectionKey key = keyIterator.next();

              if(key.isAcceptable()) {
                  // a connection was accepted by a ServerSocketChannel.

              } else if (key.isConnectable()) {
                  // a connection was established with a remote server.

              } else if (key.isReadable()) {
                  // a channel is ready for reading

              } else if (key.isWritable()) {
                  // a channel is ready for writing
                  
          //提交所需處理的代碼
              }

              //移除所有KEY
              keyIterator.remove();
            }

          posted on 2013-07-16 12:31 paulwong 閱讀(359) 評論(0)  編輯  收藏 所屬分類: J2SE性能優化

          主站蜘蛛池模板: 荔波县| 万安县| 贡山| 济宁市| 武威市| 周至县| 武夷山市| 香港 | 泰来县| 南靖县| 盐源县| 宜宾县| 攀枝花市| 正镶白旗| 南京市| 饶河县| 涿州市| 贡嘎县| 台山市| 佛山市| 吉首市| 池州市| 贵德县| 鹤山市| 迁安市| 彭州市| 泰和县| 轮台县| 威远县| 磐安县| 隆德县| 衡阳市| 寿宁县| 吉首市| 囊谦县| 通辽市| 烟台市| 尉氏县| 长沙县| 北川| 江达县|