Difference between calling close() directly and us

2019-08-07 14:15发布

问题:

I'm using netty 3.6.6.

Could someone explain about the difference between the following two codes?

  1. channel.close();

  2. channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);

When I used No 1, I found that netty sent TCP FIN before sending all packets I wrote. Consequently, the client couldn't all packets server sent. But I couldn't find a problem for No 2.

I don't understand why No 1 makes a problem. What's difference?

Thanks in advance.

回答1:

I am new to netty, here is my option: 1.will directly close the channel no matter whether or not you have unsend packets. 2.will add a listener to the channelfuture to detect if all the packets are sented and then close the channel



回答2:

From my experience: You should use Listener version.

You will get an exception if you close the channel directly and there is still data in the internal queue.

The reason why use this kind of design is: efficiency. The IO work are done by Netty IO Thread to avoid synchronization or contention.Write task will put into a queue if current thread is not IO worker thread.

You could check NioClientSocketPipelineSink.evenSunk, AbstractNioWorker and NioWorker.scheduleWriteIfNecessary

Netty are keep improving its thread model: https://github.com/netty/netty/wiki/Thread-model



标签: netty