/**
   * @param bytebuffer ByteBuffer
   * @param flip boolean
   * @return int
   * @throws IOException TODO Fix non blocking write properly
   */
  private synchronized int writeToSocket(ByteBuffer bytebuffer, boolean block, boolean flip)
      throws IOException {
    if (flip) bytebuffer.flip();

    int written = 0;
    NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) socket.getAttachment(false);
    if (att == null) throw new IOException("Key must be cancelled");
    long writeTimeout = att.getTimeout();
    Selector selector = null;
    try {
      selector = pool.get();
    } catch (IOException x) {
      // ignore
    }
    try {
      written = pool.write(bytebuffer, socket, selector, writeTimeout, block, lastWrite);
      // make sure we are flushed
      do {
        if (socket.flush(true, selector, writeTimeout, lastWrite)) break;
      } while (true);
    } finally {
      if (selector != null) pool.put(selector);
    }
    if (block) bytebuffer.clear(); // only clear
    return written;
  }
  @Override
  protected void output(byte[] src, int offset, int length) throws IOException {
    ByteBuffer writeBuffer = socketWrapper.getSocket().getBufHandler().getWriteBuffer();

    writeBuffer.put(src, offset, length);

    writeBuffer.flip();

    KeyAttachment att = (KeyAttachment) socketWrapper.getSocket().getAttachment(false);
    if (att == null) throw new IOException("Key must be cancelled");
    long writeTimeout = att.getWriteTimeout();
    Selector selector = null;
    try {
      selector = pool.get();
    } catch (IOException x) {
      // ignore
    }
    try {
      pool.write(writeBuffer, socketWrapper.getSocket(), selector, writeTimeout, true);
    } finally {
      if (selector != null) pool.put(selector);
    }
    writeBuffer.clear();
  }