隨筆-159  評論-114  文章-7  trackbacks-0

          服務器往外發數據包,不是光一個socketChannel.write(bb); 就完事了


          那是理想狀態。。

          用我方法才能保證發出,即使客戶端連接很濫

          public static long flushChannel(SocketChannel socketChannel,ByteBuffer bb, long writeTimeout) throws IOException
           
          {

               SelectionKey key 
          = null;
               Selector writeSelector 
          = null;
               
          int attempts = 0;
               
          int bytesProduced = 0;
               
          try {
                   
          while (bb.hasRemaining()) {
                       
          int len = socketChannel.write(bb);
                       attempts
          ++;
                       
          if (len < 0){
                           
          throw new EOFException();
                       }
           
                       bytesProduced 
          += len;
                       
          if (len == 0{
                           
          if (writeSelector == null){
                               writeSelector 
          = Selector.open();
                               
          if (writeSelector == null){
                                   
          // Continue using the main one
                                   continue;
                               }
           
                           }


                           key 
          = socketChannel.register(writeSelector, key.OP_WRITE);

                           
          if (writeSelector.select(writeTimeout) == 0{

                               
          if (attempts > 2)

                                   
          throw new IOException("Client disconnected");

                           }
           else {

                               attempts
          --;

                           }


                       }
           else {

                           attempts 
          = 0;

                       }


                   }


               }
           finally {

                   
          if (key != null{

                       key.cancel();

                       key 
          = null;

                   }


                   
          if (writeSelector != null{

                       
          // Cancel the key.

                       writeSelector.selectNow();

                       writeSelector.close();

                   }


               }


               
          return bytesProduced;

           }
            


          posted on 2008-11-19 12:08 北國狼人的BloG 閱讀(1448) 評論(1)  編輯  收藏

          評論:
          # re: 用戶NIO寫服務器,必須多加處理OP_WRITE,不會丟包 2010-11-09 16:14 | raymond
          好用,頂一個!  回復  更多評論
            

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 周宁县| 东阿县| 东方市| 女性| 上杭县| 叙永县| 九龙县| 田林县| 乌兰县| 毕节市| 金乡县| 宁化县| 临桂县| 平定县| 安龙县| 永定县| 澳门| 浦北县| 西昌市| 镇赉县| 独山县| 探索| 洪洞县| 衡南县| 华阴市| 泗洪县| 永胜县| 五华县| 修文县| 两当县| 乌鲁木齐县| 长汀县| 阜南县| 呈贡县| 井研县| 宜昌市| 莒南县| 舞钢市| 宁波市| 夏河县| 卢氏县|