16

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

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

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

谢谢

4

1 回答 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();
}
于 2011-02-18T10:54:19.700 回答