List of usage examples for java.nio.channels SocketChannel write
public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
From source file:org.apache.htrace.impl.PackedBufferManager.java
/** * Send the provided ByteBuffer objects. * * We use non-blocking I/O because Java does not provide write timeouts. * Without a write timeout, the socket could get hung and we'd never recover. * We also use the GatheringByteChannel#write method which calls the pread() * system call under the covers. This ensures that even if TCP_NODELAY is on, * we send the minimal number of packets. *///w w w . j a va 2s . co m private void doSend(SelectionKey sockKey, ByteBuffer[] bufs) throws IOException { long totalWritten = 0; sockKey.interestOps(SelectionKey.OP_WRITE); SocketChannel sock = (SocketChannel) sockKey.attachment(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (true) { selector.select(remainingMs); int firstBuf = 0; for (SelectionKey key : selector.selectedKeys()) { if (key.isWritable()) { long written = sock.write(bufs, firstBuf, bufs.length - firstBuf); if (LOG.isTraceEnabled()) { LOG.trace("Sent " + written + " bytes to " + conf.endpointStr); } totalWritten += written; } } while (true) { if (firstBuf == bufs.length) { if (LOG.isTraceEnabled()) { LOG.trace("Finished sending " + totalWritten + " bytes to " + conf.endpointStr); } return; } if (bufs[firstBuf].remaining() > 0) { break; } firstBuf++; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }