简体   繁体   English

Netty:如果它是一个“保持活跃”的连接,我应该关闭频道吗?

[英]Netty: Should I close the Channel if it's a 'keep-alive' connection?

I'm writing an HTTP server with Netty. 我正在用Netty编写一个HTTP服务器。 I set the keep-alive option when I create server bootstrap. 我在创建服务器引导程序时设置了keep-alive选项。 bootstrap.setOption("child.keepAlive", true); Each time I write an HTTP response, I set the keep-alive header and close the channel after writing response. 每次写HTTP响应时,我都会设置keep-alive标头并在写入响应后关闭通道。

rep.setHeader("Connection", "keep-alive");
channel.write(rep).addListener(ChannelFutureListener.CLOSE);

I'm not sure if I'm supposed to close the Channel. 我不确定我是否应该关闭频道。

Assuming that you are writing an HTTP 1.1 server, you should per default keep the connection open after sending the response. 假设您正在编写HTTP 1.1服务器,则应该在发送响应后默认保持连接处于打开状态。 If, for some reason, you decide to close it anyway , you should include 如果由于某种原因,你决定关闭它,你应该包括

Connection: close

in the response. 在回应中。

Note that 注意

bootstrap.setOption("child.keepAlive", true);

turns on the keepalive option on the socket and has nothing to do with HTTP; 打开套接字上的keepalive选项,与HTTP无关; rather, it is a kind of watchdog mechanim in order to detect broken connections in the absence of "real" traffic. 相反,它是一种监视机制,以便在没有“真实”流量的情况下检测断开的连接。

Note that you also need to specify the length of the content: 请注意,您还需要指定内容的长度:

  response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

so that the receiver can figure out where the message has ended. 这样接收者就可以找出消息的结束位置。 Else, the receive will just keep waiting for the message. 否则,接收将继续等待消息。

And, to be clear, you should not write ".addListener(ChannelFutureListener.CLOSE);" 而且,要清楚,你不应该写“.addListener(ChannelFutureListener.CLOSE);” if you want your connection to remain open. 如果您希望您的连接保持打开状态。

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

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