/*
   * Adapted from the NioOutputBuffer
   */
  public synchronized int writeToSocket(byte[] bytes, int off, int len)
      throws IOException, RemoteException {
    try {

      nioChannel.getBufHandler().getWriteBuffer().clear();
      nioChannel.getBufHandler().getWriteBuffer().put(bytes, off, len);
      nioChannel.getBufHandler().getWriteBuffer().flip();

      int written = 0;
      org.apache.tomcat.util.net.NioEndpointKeyAttachmentRemoteInterface att =
          (org.apache.tomcat.util.net.NioEndpointKeyAttachmentRemoteInterface)
              nioChannel.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(
                nioChannel.getBufHandler().getWriteBuffer(),
                nioChannel,
                selector,
                writeTimeout,
                true);
      } finally {
        if (selector != null) {
          pool.put(selector);
        }
      }
      return written;
    } catch (Exception excp) {
      excp.printStackTrace();
    }
    return 0;
  }