在netty通道上设置套接字超时

时间:2010-09-16 12:36:30

标签: netty

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

超时的目的是,如果15分钟内没有发生任何事情,将关闭未使用的频道。

虽然我没有看到任何配置这样做,但套接字本身也对我隐藏。

由于

1 个答案:

答案 0 :(得分: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));
...

当它导致超时时,使用 ReadTimeoutException 调用MyHandler.exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e)。

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    if (e.getCause() instanceof ReadTimeoutException) {
        // NOP
    }
    ctx.getChannel().close();
}