private static boolean read(SelectionKey k) { ScatteringByteChannel ch = (ScatteringByteChannel) k.channel(); NioSocketChannel channel = (NioSocketChannel) k.attachment(); ReceiveBufferSizePredictor predictor = channel.getConfig().getReceiveBufferSizePredictor(); ChannelBufferFactory bufferFactory = channel.getConfig().getBufferFactory(); ChannelBuffer buffer = bufferFactory.getBuffer(predictor.nextReceiveBufferSize()); int ret = 0; int readBytes = 0; boolean failure = true; try { while ((ret = buffer.writeBytes(ch, buffer.writableBytes())) > 0) { readBytes += ret; if (!buffer.writable()) { break; } } failure = false; } catch (AsynchronousCloseException e) { // Can happen, and does not need a user attention. } catch (Throwable t) { fireExceptionCaught(channel, t); } if (readBytes > 0) { // Update the predictor. predictor.previousReceiveBufferSize(readBytes); // Fire the event. fireMessageReceived(channel, buffer); } if (ret < 0 || failure) { close(k); return false; } return true; }