}
private void flush(DatagramSessionImpl session) throws IOException {
DatagramChannel ch = session.getChannel();
Queue writeRequestQueue = session.getWriteRequestQueue();
WriteRequest req;
for (;;) {
synchronized (writeRequestQueue) {
req = (WriteRequest) writeRequestQueue.first();
}
if (req == null)
break;
ByteBuffer buf = (ByteBuffer) req.getMessage();
if (buf.remaining() == 0) {
// pop and fire event
synchronized (writeRequestQueue) {
writeRequestQueue.pop();
}
session.increaseWrittenMessages();
buf.reset();
((DatagramFilterChain) session.getFilterChain())
.fireMessageSent(session, req);
continue;
}
SelectionKey key = session.getSelectionKey();
if (key == null) {
scheduleFlush(session);
break;
}
if (!key.isValid()) {
continue;
}
SocketAddress destination = req.getDestination();
if (destination == null) {
destination = session.getRemoteAddress();
}
int writtenBytes = ch.send(buf.buf(), destination);
if (writtenBytes == 0) {
// Kernel buffer is full
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} else if (writtenBytes > 0) {
key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
// pop and fire event
synchronized (writeRequestQueue) {
writeRequestQueue.pop();
}
session.increaseWrittenBytes(writtenBytes);
session.increaseWrittenMessages();
buf.reset();