简体   繁体   English

写入回复后立即关闭频道

[英]Closing the channel right after writing the response

What happens if I close the channel right after writing the response? 如果我在写完回复后立即关闭频道会怎样? Is the response still delivered? 回复是否仍然有效?

This http upload example seems to say that but I'm not sure if it's just a bug. 这个http上传示例似乎说了这一点,但是我不确定这是否只是一个错误。

writeResponse(ctx.channel());
ctx.channel().close();

If you close a channel using .close() just after writing, then you create a race condition in with either all the data is written, half of the data, or even none, depending on the length of the message. 如果在写入后立即使用.close()关闭通道,则将创建竞争条件,其中写入的所有数据,数据的一半,甚至没有,取决于消息的长度。

This happens because all written messages end up into a queue, and depending if the current thread is a Netty thread or not, it either processes the data directory, or just returns. 发生这种情况是因为所有已写消息最终都进入队列,并且取决于当前线程是否为Netty线程,它要么处理数据目录,要么返回。

Since in most conditions you only want to close the channel after all writes as completed, you should use the following code when writing your response: 由于在大多数情况下,您只想在所有写入完成后关闭通道,因此在编写响应时应使用以下代码:

ctx.writeAndFlush(protocolSpecificPacket)
    .addListener(ChannelFutureListener.CLOSE);

While this always works, you don't always have access to the last write, in these cases you can also send an empty ByteBuf , and then add the listener to that: 尽管这始终有效,但是您并不总是有权访问最后一次写入,在这种情况下,您还可以发送一个空的ByteBuf ,然后向其添加侦听器:

ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
    .addListener(ChannelFutureListener.CLOSE);

No it not a bug,but not the best way to close channel,I assume you writeResponse perform like this: 不,这不是一个错误,但不是关闭通道的最佳方法,我假设您的writeResponse执行如下操作:

ctx.channel().write(msg)

It's sent asynchronisly,actuallay the message will offer to a writeBufferQueue,and the write IO thread will be wake up to do the actual write. 它是异步发送的,实际上该消息将提供给writeBufferQueue,并且写IO线程将被唤醒以进行实际写操作。

Check the ChannelFuture returned by ctx.channel().write(msg),you can wait on that object. 检查ctx.channel()。write(msg)返回的ChannelFuture ,可以等待该对象。

the best way to close a netty channel,I think,would be : 我认为,关闭网络渠道的最佳方法是:

ctx.channel().write(a emptybuffer).addFutureListener(Channels.CloseFuture);

since you are using netty 4.0,you may neeed to search something similar with above. 由于您使用的是netty 4.0,因此您可能需要搜索与上述类似的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM