我有一个Netty频道,我想在基础插座上设置一个超时(默认设置为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));
...

当它导致超时时,myhandler.exceptioncought(ChannelHandlerContext CTX,ExceptionEvent e)。 ReadTimeOutException.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    if (e.getCause() instanceof ReadTimeoutException) {
        // NOP
    }
    ctx.getChannel().close();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top