/** * @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; }
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; } }
@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(); }