gpt4 book ai didi

netty - 在 netty channel 上设置套接字超时

转载 作者:行者123 更新时间:2023-12-03 14:55:58 28 4
gpt4 key购买 nike

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

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

虽然我没有看到任何配置这样做,而且 socket 本身也对我隐藏。

谢谢

最佳答案

如果使用 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) 被调用 读取超时异常 .

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

关于netty - 在 netty channel 上设置套接字超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3726696/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com