I'm writing an HTTP server with Netty. I set the keep-alive option when I create server bootstrap.
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.
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. 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; 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);" if you want your connection to remain open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With