首页 > 解决方案 > 为什么在 Netty 用户指南中调用 ctx.write() 后没有调用 ctx.flush()?

问题描述

nettyJava 文档中是这样说的so be sure to call flush() once you want to request to flush,但在这个例子中它说没有必要调用ctx.flush(). 但我没有发现flush(ChannelHandlerContext ctx)被称为如它所说的那样。

package io.netty.example.time;

public class TimeEncoder extends ChannelOutboundHandlerAdapter {
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        UnixTime m = (UnixTime) msg;
        ByteBuf encoded = ctx.alloc().buffer(4);
        encoded.writeInt((int)m.value());
        ctx.write(encoded, promise); // (1)
    }
}

Second, we did not call ctx.flush(). There is a separate handler method void flush(ChannelHandlerContext ctx) which is purposed to override the flush() operation. https://netty.io/wiki/user-guide-for-4.x.html#wiki-h3-8

标签: javanetty

解决方案


缓冲的重点是你将一堆数据“收集”在一起并一次发送,因为发送大量数据的速度与发送少量数据的速度大致相同(因为 IO 很慢)。

这是分配一个 4 字节的缓冲区。如果您每 4 个字节刷新一次,则效率不会很高。

在某个地方会有一个刷新,只是不是在这个特定的方法中。


推荐阅读