Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 784
woodings Avatar asked Nov 28 '12 09:11

woodings


2 Answers

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.

like image 112
forty-two Avatar answered Nov 20 '22 12:11

forty-two


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.

like image 36
Vivek Pandey Avatar answered Nov 20 '22 11:11

Vivek Pandey