Jack Zhou
Jack Zhou

Reputation: 11

Will netty automatically flush writed data?

Recently I was writing a http server and I transplanted some netty components to my project. When I read the source code of netty's ChannelHandlerContext, I found that actually it doesn't flush into socket. I knew that I have to invoke flush() to flush the internal buffer into socket.

So I wonder will netty automatically flush the internal buffer, I have read some source code, but I am not good at it. And I googled but none answered it, the only answer I got is do flushing.

What I have learned from source code is: write continue writing into outboundbuffer, and if outboundbuffer reaches highwatermark, it will fire writability changed event and the channel is unwritable.

Upvotes: 1

Views: 1642

Answers (3)

a.l.
a.l.

Reputation: 1135

No, it won't.

However, it could be implemented quite easily.

As you said:

What I have learned from source code is: write continue writing into outboundbuffer, and if outboundbuffer reaches highwatermark, it will fire writability changed event and the channel is unwritable.

It's right. and it in fact tells a way to automaticallly flush. Just override ChannelInboundHandler.channelWritabilityChanged to call flush().

Upvotes: 0

Yang Zhou
Yang Zhou

Reputation: 54

4.0 introduced a new operation called flush() which explicitly flushes the outbound buffer of a Channel, and write() operation does not flush automatically. You can think of this as a java.io.BufferedOutputStream, except that it works at message level.

Because of this change, you must be very careful not to forget to call ctx.flush() after writing something. Alternatively, you could use a shortcut method writeAndFlush().

I found it at https://netty.io/wiki/new-and-noteworthy-in-4.0.html#write-does-not-flush-automatically

In fact, I have the similar question at Why did not call ctx.flush() after ctx.write() is called at Netty user guide?

Please contact me if you got the answer.

Upvotes: 0

BeyondPerception
BeyondPerception

Reputation: 524

You can call the writeAndFlush method if you want to do it in one line, but otherwise you need to flush or you data will not go through.

Upvotes: 1

Related Questions