{
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();
}
req.getFuture().setWritten( true );
session.increaseWrittenWriteRequests();
( ( DatagramFilterChain ) session.getFilterChain() ).messageSent( session, buf );
continue;
}
SelectionKey key = session.getSelectionKey();
if( key == null )
{
scheduleFlush( session );
break;
}
if( !key.isValid() )
{
continue;
}
int pos = buf.position();
int writtenBytes = ch
.send( buf.buf(), session.getRemoteAddress() );
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 );
req.getFuture().setWritten( true );
session.increaseWrittenWriteRequests();
( ( DatagramFilterChain ) session.getFilterChain() ).messageSent( session, buf.position( pos ) );
}
}
}