隨筆-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
          好用,頂一個!  回復  更多評論
            

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


          網站導航:
           
          主站蜘蛛池模板: 安龙县| 胶州市| 英吉沙县| 淮滨县| 岳西县| 新津县| 津市市| 察隅县| 育儿| 吴堡县| 浙江省| 临澧县| 攀枝花市| 英超| 元朗区| 金平| 蓝田县| 开远市| 乌苏市| 色达县| 息烽县| 东至县| 友谊县| 松桃| 长汀县| 宽城| 雷波县| 方正县| 宣武区| 淮阳县| 隆化县| 陆丰市| 邯郸市| 长沙市| 辽宁省| 咸阳市| 三都| 陇西县| 黎川县| 元朗区| 皋兰县|