Skip to content
Advertisement

Netty writeAndFlush() incomplete

My tcp client request netty server, and netty server use writeAndFlush() return 393718 bytes. But the client only receive 262142 bytes. I use “tcpdump -A” to apturing packets, less than 393718 too. So I think the properble is in netty writeAndFlush() function?

Here is the code

tcp server:

JavaScript

server handler:

JavaScript

tcp client:

JavaScript

Advertisement

Answer

You close the connection directly after writing, in a async framework, this is asking for trouble.

What is happening here, is that a new incoming message arrives in your channelRead by a Netty thread. This message is then progressed through your handler, and finally, it’s being sent back using writeAndFlush, however, this call of sending the data back happens partly in the background, and so the code continues on forward, then it sees the call to close the connection, it happily does that at this point, since you told it.

What happens at this point is a race condition between the TCP layer trying to send the data, and the TCP layer receiving the call to close the connection, because of the buffers used in different parts of the layers, it happens so that the limit is at 262142 bytes, however this limit may fluctuate if unknown aspects change of the connection.

A solution for this problem is waiting till Netty says the write is successful, and only then close it. Since we don’t want to wait in a async application, this means we must register a listener, luck is on our side this case, and netty provides us with a listener that just closes the channel for us. You can use it like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement