随笔-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 阅读(1444) 评论(1)  编辑  收藏

评论:
# re: 用户NIO写服务器,必须多加处理OP_WRITE,不会丢包 2010-11-09 16:14 | raymond
好用,顶一个!  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: