I have a question regarding configuration of timeouts on a netty TCP server. Right now, I set the connect timout like this:
serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);
This seems to work, all good and well. Now I wonder if it's possible to define a "read timeout" on the server side. The idea would be that the server worker thread is interrupted when the read timeout elapses, so that it becomes available for other tasks. When I try to set the read timeout as follows I get an "unsupported channel option" warning at start-up:
serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);
Is there a way to achieve a "read/processing timeout" on the server-side of things? Any help is appreciated.
Kind Regards, Michael
Add a ReadTimeoutHandler
to the first position of your pipeline:
http://netty.io/4.0/api/io/netty/handler/timeout/ReadTimeoutHandler.html
public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter
// Raises a ReadTimeoutException when no data was read within a certain period of time.
// The connection is closed when there is no inbound traffic
// for 30 seconds.
public class MyChannelInitializer extends ChannelInitializer<Channel> {
public void initChannel(Channel channel) {
channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(30);
channel.pipeline().addLast("myHandler", new MyHandler());
}
}
// Handler should handle the ReadTimeoutException.
public class MyHandler extends ChannelDuplexHandler {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
if (cause instanceof ReadTimeoutException) {
// do something
} else {
super.exceptionCaught(ctx, cause);
}
}
}
ServerBootstrap bootstrap = ...;
...
bootstrap.childHandler(new MyChannelInitializer());
...
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