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

          主站蜘蛛池模板: 海盐县| 罗甸县| 东兴市| 安溪县| 玉林市| 方正县| 阳新县| 贵州省| 迁西县| 宝应县| 富宁县| 嘉善县| 平昌县| 财经| 古田县| 栾川县| 瑞丽市| 甘泉县| 阳山县| 汉川市| 镇赉县| 黄浦区| 华安县| 多伦县| 安宁市| 梅州市| 长春市| 罗城| 沅江市| 综艺| 安宁市| 定襄县| 五指山市| 安吉县| 蒙山县| 略阳县| 镇宁| 墨江| 邳州市| 郎溪县| 鄢陵县|