/** * Method tryReadPacket2. * * @param key SelectionKey * @param con MMOConnection<T> * @param buf ByteBuffer * @return boolean */ protected boolean tryReadPacket2(SelectionKey key, MMOConnection<T> con, ByteBuffer buf) { if (con.isClosed()) { return false; } int pos = buf.position(); if (buf.remaining() > _sc.HEADER_SIZE) { int size = buf.getShort() & 0xffff; if ((size <= _sc.HEADER_SIZE) || (size > _sc.PACKET_SIZE)) { _log.error( "Incorrect packet size : " + size + "! Client : " + con.getClient() + ". Closing connection."); closeConnectionImpl(con); return false; } size -= _sc.HEADER_SIZE; if (size <= buf.remaining()) { stats.increaseIncomingPacketsCount(); parseClientPacket(getPacketHandler(), buf, size, con); buf.position(pos + size + _sc.HEADER_SIZE); if (!buf.hasRemaining()) { freeBuffer(buf, con); return false; } return true; } buf.position(pos); } if (pos == buf.capacity()) { _log.warn( "Read buffer exhausted for client : " + con.getClient() + ", try to adjust buffer size, current : " + buf.capacity() + ", primary : " + (buf == READ_BUFFER) + "."); } if (buf == READ_BUFFER) { allocateReadBuffer(con); } else { buf.compact(); } return false; }
/** * Method readPacket. * * @param key SelectionKey */ protected void readPacket(SelectionKey key) { MMOConnection<T> con = (MMOConnection<T>) key.attachment(); if (con.isClosed()) { return; } ByteBuffer buf; int result = -2; if ((buf = con.getReadBuffer()) == null) { buf = READ_BUFFER; } // if we try to to do a read with no space in the buffer it will read 0 bytes // going into infinite loop if (buf.position() == buf.limit()) { _log.error( "Read buffer exhausted for client : " + con.getClient() + ", try to adjust buffer size, current : " + buf.capacity() + ", primary : " + (buf == READ_BUFFER) + ". Closing connection."); closeConnectionImpl(con); } else { try { result = con.getReadableByteChannel().read(buf); } catch (IOException e) { // error handling goes bellow } if (result > 0) { buf.flip(); stats.increaseIncomingBytes(result); @SuppressWarnings("unused") int i; for (i = 0; this.tryReadPacket2(key, con, buf); i++) {} } else if (result == 0) { closeConnectionImpl(con); } else if (result == -1) { closeConnectionImpl(con); } else { con.onForcedDisconnection(); closeConnectionImpl(con); } } if (buf == READ_BUFFER) { buf.clear(); } }