/** * Method writePacket. * * @param key SelectionKey */ protected void writePacket(SelectionKey key) { MMOConnection<T> con = (MMOConnection<T>) key.attachment(); prepareWriteBuffer(con); DIRECT_WRITE_BUFFER.flip(); int size = DIRECT_WRITE_BUFFER.remaining(); int result = -1; try { result = con.getWritableChannel().write(DIRECT_WRITE_BUFFER); } catch (IOException e) { // error handling goes on the if bellow } // check if no error happened if (result >= 0) { stats.increaseOutgoingBytes(result); // check if we written everything if (result != size) { con.createWriteBuffer(DIRECT_WRITE_BUFFER); } if (!con.getSendQueue().isEmpty() || con.hasPendingWriteBuffer()) { con.scheduleWriteInterest(); } } else { con.onForcedDisconnection(); closeConnectionImpl(con); } }
/** * 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(); } }