@Override protected int doWriteMessages(MessageBuf<Object> buf, boolean lastSpin) throws Exception { DatagramPacket packet = (DatagramPacket) buf.peek(); ByteBuf data = packet.data(); int dataLen = data.readableBytes(); ByteBuffer nioData; if (data.nioBufferCount() == 1) { nioData = data.nioBuffer(); } else { nioData = ByteBuffer.allocate(dataLen); data.getBytes(data.readerIndex(), nioData); nioData.flip(); } final int writtenBytes = javaChannel().send(nioData, packet.remoteAddress()); final SelectionKey key = selectionKey(); final int interestOps = key.interestOps(); if (writtenBytes <= 0 && dataLen > 0) { // Did not write a packet. // 1) If 'lastSpin' is false, the caller will call this method again real soon. // - Do not update OP_WRITE. // 2) If 'lastSpin' is true, the caller will not retry. // - Set OP_WRITE so that the event loop calls flushForcibly() later. if (lastSpin) { if ((interestOps & SelectionKey.OP_WRITE) == 0) { key.interestOps(interestOps | SelectionKey.OP_WRITE); } } return 0; } // Wrote a packet. buf.remove(); // packet was written free up buffer packet.free(); if (buf.isEmpty()) { // Wrote the outbound buffer completely - clear OP_WRITE. if ((interestOps & SelectionKey.OP_WRITE) != 0) { key.interestOps(interestOps & ~SelectionKey.OP_WRITE); } } return 1; }