Skip to content

netty socket_write

wangkaiwu edited this page Apr 16, 2022 · 5 revisions

netty socket write

write 方法

public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
    @Override
    public ChannelFuture write(Object msg) {
        return pipeline.write(msg);
    }
}

tail context

abstract class AbstractChannelHandlerContext implements ChannelHandlerContext, ResourceLeakHint {
    @Override
    public ChannelFuture write(final Object msg, final ChannelPromise promise) {
        write(msg, false, promise);
        return promise;
    }

    private void write(Object msg, boolean flush, ChannelPromise promise) {
        final AbstractChannelHandlerContext next = findContextOutbound(flush ?
                (MASK_WRITE | MASK_FLUSH) : MASK_WRITE);
        final Object m = pipeline.touch(msg, next);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
        } else {
            final WriteTask task = WriteTask.newInstance(next, m, promise, flush);
            if (!safeExecute(executor, task, promise, m, !flush)) {
                task.cancel();
            }
        }
    }

    private static boolean safeExecute(EventExecutor executor, Runnable runnable,
                                       ChannelPromise promise, Object msg, boolean lazy) {
        if (lazy && executor instanceof AbstractEventExecutor) {
            ((AbstractEventExecutor) executor).lazyExecute(runnable);
        }
        return true;
    }
}
public abstract class SingleThreadEventExecutor extends AbstractScheduledEventExecutor implements OrderedEventExecutor {
    // 默认是 false
    private final boolean addTaskWakesUp;

    @Override
    public void lazyExecute(Runnable task) {
        execute(ObjectUtil.checkNotNull(task, "task"), false);
    }

    private void execute(Runnable task, boolean immediate) {
        addTask(task);
        if (!inEventLoop) {
            startThread();
        }
        // lazy 的意思是不执行 wakeup
        if (!addTaskWakesUp && immediate) {
            wakeup(inEventLoop);
        }
    }
}
static final class WriteTask implements Runnable {
    private static final ObjectPool<WriteTask> RECYCLER = ObjectPool.newPool(new ObjectCreator<WriteTask>() {
        @Override
        public WriteTask newObject(Handle<WriteTask> handle) {
            return new WriteTask(handle);
        }
    });

    static WriteTask newInstance(AbstractChannelHandlerContext ctx,
                                 Object msg, ChannelPromise promise, boolean flush) {
        WriteTask task = RECYCLER.get();
        init(task, ctx, msg, promise, flush);
        return task;
    }

    protected static void init(WriteTask task, AbstractChannelHandlerContext ctx,
                               Object msg, ChannelPromise promise, boolean flush) {
        task.ctx = ctx;
        task.msg = msg;
        task.promise = promise;
        if (ESTIMATE_TASK_SIZE_ON_SUBMIT) {
            task.size = ctx.pipeline.estimatorHandle().size(msg) + WRITE_TASK_OVERHEAD;
            ctx.pipeline.incrementPendingOutboundBytes(task.size);
        }
    }

    @Override
    public void run() {
        try {
            decrementPendingOutboundBytes();
            if (size >= 0) {
                ctx.invokeWrite(msg, promise);
            }
        } finally {
            recycle();
        }
    }
}
abstract class AbstractChannelHandlerContext implements ChannelHandlerContext, ResourceLeakHint {
    void invokeWrite(Object msg, ChannelPromise promise) {
        if (invokeHandler()) {
            invokeWrite0(msg, promise);
        }
    }

    private void invokeWrite0(Object msg, ChannelPromise promise) {
        // 调用 head context 的 write 方法
        ((ChannelOutboundHandler) handler()).write(this, msg, promise);
    }
}

head context

final class HeadContext extends AbstractChannelHandlerContext
        implements ChannelOutboundHandler, ChannelInboundHandler {
    private final Unsafe unsafe;

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        unsafe.write(msg, promise);
    }
}
protected abstract class AbstractUnsafe implements Unsafe {
    private volatile ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this);

    @Override
    public final void write(Object msg, ChannelPromise promise) {
        ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
        int size;
        msg = filterOutboundMessage(msg);
        size = pipeline.estimatorHandle().size(msg);
        if (size < 0) {
            size = 0;
        }
        outboundBuffer.addMessage(msg, size, promise);
    }
}
public abstract class AbstractNioByteChannel extends AbstractNioChannel {
    @Override
    protected final Object filterOutboundMessage(Object msg) {
        if (msg instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf) msg;
            if (buf.isDirect()) {
                return msg;
            }
            return newDirectBuffer(buf);
        }
        if (msg instanceof FileRegion) {
            return msg;
        }
        throw new UnsupportedOperationException(
                "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
    }
}
public final class ChannelOutboundBuffer {
    // 被刷新的链表结构中第一个条目
    private Entry flushedEntry;
    // 链表结构中第一个未刷新的条目
    private Entry unflushedEntry;
    // 表示缓冲区尾部的条目
    private Entry tailEntry;

    public void addMessage(Object msg, int size, ChannelPromise promise) {
        Entry entry = Entry.newInstance(msg, size, total(msg), promise);
        if (tailEntry == null) {
            flushedEntry = null;
        } else {
            // 将自己放到链表的尾部
            Entry tail = tailEntry;
            tail.next = entry;
        }
        // 自己成为尾部
        tailEntry = entry;
        if (unflushedEntry == null) {
            // 自己作为未刷新的条目
            unflushedEntry = entry;
        }
        incrementPendingOutboundBytes(entry.pendingSize, false);
    }

    private void incrementPendingOutboundBytes(long size, boolean invokeLater) {
        if (size == 0) {
            return;
        }
        long newWriteBufferSize = TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, size);
        if (newWriteBufferSize > channel.config().getWriteBufferHighWaterMark()) {
            setUnwritable(invokeLater);
        }
    }
}

flush 方法

public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
    @Override
    public Channel flush() {
        pipeline.flush();
        return this;
    }
}
abstract class AbstractChannelHandlerContext implements ChannelHandlerContext, ResourceLeakHint {
    @Override
    public ChannelHandlerContext flush() {
        final AbstractChannelHandlerContext next = findContextOutbound(MASK_FLUSH);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeFlush();
        }
    }
}

Clone this wiki locally