/**
   * @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;
  }
Пример #2
0
 private int readSocket(byte[] buf, int pos, int n, boolean block) throws IOException {
   int nRead = 0;
   ByteBuffer readBuffer = socketWrapper.getSocket().getBufHandler().getReadBuffer();
   readBuffer.clear();
   readBuffer.limit(n);
   if (block) {
     Selector selector = null;
     try {
       selector = pool.get();
     } catch (IOException x) {
       // Ignore
     }
     try {
       NioEndpoint.KeyAttachment att =
           (NioEndpoint.KeyAttachment) socketWrapper.getSocket().getAttachment(false);
       if (att == null) throw new IOException("Key must be cancelled.");
       nRead = pool.read(readBuffer, socketWrapper.getSocket(), selector, att.getTimeout());
     } catch (EOFException eof) {
       nRead = -1;
     } finally {
       if (selector != null) pool.put(selector);
     }
   } else {
     nRead = socketWrapper.getSocket().read(readBuffer);
   }
   if (nRead > 0) {
     readBuffer.flip();
     readBuffer.limit(nRead);
     readBuffer.get(buf, pos, nRead);
     return nRead;
   } else if (nRead == -1) {
     // return false;
     throw new EOFException(sm.getString("iib.eof.error"));
   } else {
     return 0;
   }
 }