2012-05-31 70 views
1

我試圖從一個頻道重複寫入和讀取,但在第二次寫入嘗試時失敗,因爲在讀取第一個響應之後該頻道已被NioWorker關閉。是否可以重複寫入和讀取頻道?

我搜索了一整天,但沒有找到任何線索。我該怎麼做才能在同一個通道上執行寫 - 讀 - 寫 - 讀操作?的org.jboss.netty.channel.socket.nio.NioWorker源代碼

部分:除非用戶關閉它或者對等關閉它

private void processSelectedKeys(Set<SelectionKey> selectedKeys) throws IOException { 
    for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) { 
     SelectionKey k = i.next(); 
     i.remove(); 
     try { 
      int readyOps = k.readyOps(); 
      if ((readyOps & SelectionKey.OP_READ) != 0 || readyOps == 0) { 
       if (!read(k)) { 
        // Connection already closed - no need to handle write. 
        continue; 
       } 
      } 
      if ((readyOps & SelectionKey.OP_WRITE) != 0) { 
       writeFromSelectorLoop(k); 
      } 
     } catch (CancelledKeyException e) { 
      close(k); 
     } 

     if (cleanUpCancelledKeys()) { 
      break; // break the loop to avoid ConcurrentModificationException 
     } 
    } 
} 

private boolean read(SelectionKey k) { 
    final SocketChannel ch = (SocketChannel) k.channel(); 
    final NioSocketChannel channel = (NioSocketChannel) k.attachment(); 

    final ReceiveBufferSizePredictor predictor = 
     channel.getConfig().getReceiveBufferSizePredictor(); 
    final int predictedRecvBufSize = predictor.nextReceiveBufferSize(); 

    int ret = 0; 
    int readBytes = 0; 
    boolean failure = true; 

    ByteBuffer bb = recvBufferPool.acquire(predictedRecvBufSize); 
    try { 
     while ((ret = ch.read(bb)) > 0) { 
      readBytes += ret; 
      if (!bb.hasRemaining()) { 
       break; 
      } 
     } 
     failure = false; 
    } catch (ClosedChannelException e) { 
     // Can happen, and does not need a user attention. 
    } catch (Throwable t) { 
     fireExceptionCaught(channel, t); 
    } 

    if (readBytes > 0) { 
     bb.flip(); 

     final ChannelBufferFactory bufferFactory = 
      channel.getConfig().getBufferFactory(); 
     final ChannelBuffer buffer = bufferFactory.getBuffer(readBytes); 
     buffer.setBytes(0, bb); 
     buffer.writerIndex(readBytes); 

     recvBufferPool.release(bb); 

     // Update the predictor. 
     predictor.previousReceiveBufferSize(readBytes); 

     // Fire the event. 
     fireMessageReceived(channel, buffer); 
    } else { 
     recvBufferPool.release(bb); 
    } 

    // NioWorker closes the channel, making it impossible to write additional messages. 
    if (ret < 0 || failure) { 
     k.cancel(); // Some JDK implementations run into an infinite loop without this. 
     close(channel, succeededFuture(channel)); 
     return false; 
    } 

    return true; 
} 
+0

你對於忽略'ClosedChannelException'非常傲慢。這*不能*發生,除非你的應用程序有錯誤。 – EJP

回答

1

的Netty不會關閉的連接。請確保沒有發生異常。

相關問題