public Object readObject(Connection connection) throws IOException { SocketChannel socketChannel = this.socketChannel; if (socketChannel == null) throw new SocketException("Connection is closed."); if (currentObjectLength == 0) { // Read the length of the next object from the socket. int lengthLength = serialization.getLengthLength(); if (readBuffer.remaining() < lengthLength) { readBuffer.compact(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); lastReadTime = System.currentTimeMillis(); if (readBuffer.remaining() < lengthLength) return null; } currentObjectLength = serialization.readLength(readBuffer); if (currentObjectLength <= 0) throw new KryoNetException("Invalid object length: " + currentObjectLength); if (currentObjectLength > readBuffer.capacity()) throw new KryoNetException( "Unable to read object larger than read buffer: " + currentObjectLength); } int length = currentObjectLength; if (readBuffer.remaining() < length) { // Fill the tcpInputStream. readBuffer.compact(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); lastReadTime = System.currentTimeMillis(); if (readBuffer.remaining() < length) return null; } currentObjectLength = 0; int startPosition = readBuffer.position(); int oldLimit = readBuffer.limit(); readBuffer.limit(startPosition + length); Object object; try { object = serialization.read(connection, readBuffer); } catch (Exception ex) { throw new KryoNetException("Error during deserialization.", ex); } readBuffer.limit(oldLimit); if (readBuffer.position() - startPosition != length) throw new KryoNetException( "Incorrect number of bytes (" + (startPosition + length - readBuffer.position()) + " remaining) used to deserialize object: " + object); return object; }