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 閱讀(357) 評論(0)  編輯  收藏 所屬分類: J2SE 、性能優化

          主站蜘蛛池模板: 衢州市| 泗洪县| 双江| 宜君县| 昭觉县| 阿城市| 太谷县| 沅陵县| 扶余县| 广东省| 高尔夫| 诸暨市| 丹阳市| 葫芦岛市| 黎平县| 建水县| 灵台县| 石阡县| 会东县| 阆中市| 竹溪县| 潜山县| 敦化市| 牡丹江市| 迁西县| 威宁| 岐山县| 金华市| 大姚县| 柘城县| 牙克石市| 镇江市| 洞口县| 清苑县| 剑河县| 宁陕县| 龙口市| 襄城县| 丘北县| 瑞丽市| 乡城县|