public void handleWritable(java.nio.channels.Channel channel) {
BaseXnioChannel c = XnioChannelRegistry.getChannel(channel);
int writtenBytes = 0;
boolean open = true;
boolean addOpWrite = false;
MessageEvent evt;
ChannelBuffer buf;
int bufIdx;
Queue<MessageEvent> writeBuffer = c.writeBuffer;
synchronized (c.writeLock) {
evt = c.currentWriteEvent;
for (;;) {
if (evt == null) {
evt = writeBuffer.poll();
if (evt == null) {
c.currentWriteEvent = null;
break;
}
buf = (ChannelBuffer) evt.getMessage();
bufIdx = buf.readerIndex();
} else {
buf = (ChannelBuffer) evt.getMessage();
bufIdx = c.currentWriteIndex;
}
try {
final int writeSpinCount = c.getConfig().getWriteSpinCount();
boolean sent = false;
for (int i = writeSpinCount; i > 0; i --) {
if (channel instanceof GatheringByteChannel) {
int localWrittenBytes = buf.getBytes(
bufIdx,
(GatheringByteChannel) channel,
buf.writerIndex() - bufIdx);
if (localWrittenBytes != 0) {
bufIdx += localWrittenBytes;
writtenBytes += localWrittenBytes;
break;
}
} else if (channel instanceof MultipointWritableMessageChannel) {
ByteBuffer nioBuf = buf.toByteBuffer(bufIdx, buf.writerIndex() - bufIdx);
int nioBufSize = nioBuf.remaining();
SocketAddress remoteAddress = evt.getRemoteAddress();
if (remoteAddress == null) {
remoteAddress = c.getRemoteAddress();
}
sent = ((MultipointWritableMessageChannel) channel).send(remoteAddress, nioBuf);
if (sent) {
bufIdx += nioBufSize;
writtenBytes += nioBufSize;
break;
}
} else if (channel instanceof WritableMessageChannel) {
ByteBuffer nioBuf = buf.toByteBuffer(bufIdx, buf.writerIndex() - bufIdx);
int nioBufSize = nioBuf.remaining();
sent = ((WritableMessageChannel) channel).send(nioBuf);
if (sent) {
bufIdx += nioBufSize;
writtenBytes += nioBufSize;
break;
}
} else {
throw new IllegalArgumentException("Unsupported channel type: " + channel.getClass().getName());
}
}
if (bufIdx == buf.writerIndex() || sent) {
// Successful write - proceed to the next message.
evt.getFuture().setSuccess();
evt = null;
} else {
// Not written fully - perhaps the kernel buffer is full.
c.currentWriteEvent = evt;
c.currentWriteIndex = bufIdx;
addOpWrite = true;
break;
}
} catch (AsynchronousCloseException e) {
// Doesn't need a user attention - ignore.
} catch (Throwable t) {
evt.getFuture().setFailure(t);
evt = null;
fireExceptionCaught(c, t);
if (t instanceof IOException) {
open = false;
c.closeNow(succeededFuture(c));