Netty - 配置TCP服务器的超时时间

6

我有一个关于netty TCP服务器超时配置的问题。目前,我像这样设置连接超时

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);

这似乎有效,一切都很好。现在我想知道是否可能在服务器端定义“读取超时”。想法是当读取超时时间到达时,服务器工作线程被中断,以便它可以用于其他任务。当我尝试设置读取超时如下所示时,我在启动时收到“不支持的通道选项”警告:

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);

有没有一种方法可以在服务器端实现“读取/处理超时”?非常感谢您的帮助。

祝好, 迈克尔

1个回答

9
在您的管道的第一个位置添加一个ReadTimeoutHandlerhttp://netty.io/4.0/api/io/netty/handler/timeout/ReadTimeoutHandler.html
public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter

// Raises a ReadTimeoutException when no data was read within a certain period of time.

// The connection is closed when there is no inbound traffic
// for 30 seconds.

public class MyChannelInitializer extends ChannelInitializer<Channel> {
    public void initChannel(Channel channel) {
        channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(30);
        channel.pipeline().addLast("myHandler", new MyHandler());
    }
}

// Handler should handle the ReadTimeoutException.
public class MyHandler extends ChannelDuplexHandler {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        if (cause instanceof ReadTimeoutException) {
            // do something
        } else {
            super.exceptionCaught(ctx, cause);
        }
    }
}

ServerBootstrap bootstrap = ...;
...
bootstrap.childHandler(new MyChannelInitializer());
...

啊,太完美了,ReadTimeoutHandler 怎么就逃过了我的注意呢。谢谢你。 - Michael Schmid

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