隨筆-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 閱讀(1450) 評論(1)  編輯  收藏

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

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


          網站導航:
           
          主站蜘蛛池模板: 灯塔市| 阿拉善右旗| 肇庆市| 兴安县| 大同县| 内丘县| 广平县| 嵊州市| 洛扎县| 明星| 张掖市| 昔阳县| 乌兰县| 宁晋县| 兴安县| 墨竹工卡县| 广州市| 祥云县| 白玉县| 蕲春县| 繁昌县| 逊克县| 新晃| 宜州市| 莱阳市| 正定县| 惠东县| 苏尼特左旗| 阜新市| 西华县| 琼中| 漳州市| 香港| 长岛县| 昭通市| 克山县| 林州市| 吴桥县| 玉龙| 论坛| 陈巴尔虎旗|