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 、性能優化

          主站蜘蛛池模板: 孟州市| 唐海县| 泰顺县| 常德市| 曲麻莱县| 荥阳市| 嘉荫县| 西乌珠穆沁旗| 新河县| 珠海市| 炉霍县| 嘉善县| 张家界市| 黄陵县| 台东县| 赤水市| 墨竹工卡县| 大港区| 惠来县| 宝清县| 佛教| 乳源| 长岛县| 许昌市| 特克斯县| 交城县| 千阳县| 苍南县| 台北县| 于都县| 金平| 聊城市| 牙克石市| 奇台县| 公主岭市| 通山县| 巫山县| 务川| 行唐县| 鄂伦春自治旗| 珠海市|