Example #1
0
  /**
   * 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;
  }