Netty - 写入通道直到它可写

时间:2015-06-30 11:49:05

标签: java networking netty nio

根据this,要确定频道的可写性,我们可以调用channel.isWritable然后写入频道可写

即:

private void writeIfPossible(Channel channel) {
    while(needsToWrite && channel.isWritable()) {
        channel.writeAndFlush(createMessage());
    }
}

但是,这个怎么样:

private void writeIfPossible(ChannelHandlerContext ctx) {
    Channel channel = ctx.channel();
    channel.eventLoop().execute(() -> {
        while (needsToWrite && channel.isWritable()) {
            ctx.write(createMessage(), ctx.voidPromise());
        }
        ctx.flush();
    });
}

这是对的吗?我的意思是,channel.write(或ctx.write)对频道的可写性有影响吗?或者我们必须在每次写作后调用channel.flush

感谢。

2 个答案:

答案 0 :(得分:4)

Data is only really written out to the underlying socket if you call flush(). So if you never call flush() it will isWritable() will continue to return false until you may see an OOME. Whenever you call flush() is up to you and depends on how much you want to buffer before trying to flush etc.

答案 1 :(得分:0)

非常感谢毛雷尔先生。

我最终得到了这个:

public void sendMessages(ChannelHandlerContext ctx, RecyclableArrayList messages) {
    Channel channel = ctx.channel();
    channel.eventLoop().execute(() -> {
        int i = 0;
        while (channel.isActive() && channel.isWritable() && i < messages.size()) {
            for (int j = 0; j < 5 && i < messages.size(); j++, i++) {
                ctx.write(messages.get(i), ctx.voidPromise());
            }
            ctx.flush();
        }
        if (i < messages.size()) {
            messages.subList(0, i).clear();
            storeMessages(ctx.name(), messages);
        } else {
            messages.recycle();
        }
    });
}

我感谢任何其他建议。