在Netty通道上设置套接字超时时间

16

我有一个Netty通道,我想在底层套接字上设置超时(默认设置为0)。

超时的目的是,如果通道未被使用且在15分钟内没有任何活动,它将被关闭。

尽管我没有看到任何可进行配置的选项,并且套接字本身也对我隐藏。

谢谢

1个回答

15
如果使用ReadTimeoutHandler类,可以控制超时时间。
以下是Javadoc的引用。
public class MyPipelineFactory implements ChannelPipelineFactory {
    private final Timer timer;
    public MyPipelineFactory(Timer timer) {
        this.timer = timer;
    }

    public ChannelPipeline getPipeline() {
        // An example configuration that implements 30-second read timeout:
        return Channels.pipeline(
            new ReadTimeoutHandler(timer, 30), // timer must be shared.
            new MyHandler());
    }
}


ServerBootstrap bootstrap = ...;
Timer timer = new HashedWheelTimer();
...
bootstrap.setPipelineFactory(new MyPipelineFactory(timer));
...

当超时发生时,会调用MyHandler.exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e),并抛出ReadTimeoutException异常。
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    if (e.getCause() instanceof ReadTimeoutException) {
        // NOP
    }
    ctx.getChannel().close();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接