Netty - 写入通道直到它可写
Netty - write to a channel until it is writable
根据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
?
谢谢。
只有在调用 flush() 时,数据才会真正写入底层套接字。因此,如果您从不调用 flush() ,它 isWritable() 将继续 return false 直到您看到 OOME。何时调用 flush() 取决于您,并且取决于您在尝试刷新之前要缓冲多少等
非常感谢 Maurer 先生。
我最终得到了这个:
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();
}
});
}
如果有任何其他建议,我将不胜感激。
根据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
?
谢谢。
只有在调用 flush() 时,数据才会真正写入底层套接字。因此,如果您从不调用 flush() ,它 isWritable() 将继续 return false 直到您看到 OOME。何时调用 flush() 取决于您,并且取决于您在尝试刷新之前要缓冲多少等
非常感谢 Maurer 先生。
我最终得到了这个:
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();
}
});
}
如果有任何其他建议,我将不胜感激。