用户NIO写服务器,必须多加处理OP_WRITE,不会丢包

用户NIO写服务器,必须多加处理OP_WRITE,不会丢包

服务器往外发数据包,不是光一个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;

 }
  


你可能感兴趣的:(用户NIO写服务器,必须多加处理OP_WRITE,不会丢包)