【问题标题】:netty - configure timeouts on TCP servernetty - 在 TCP 服务器上配置超时
【发布时间】:2017-09-29 22:25:51
【问题描述】:

我有一个关于 netty TCP 服务器上的超时配置的问题。现在,我像这样设置 connect timout

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);

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

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);

有没有办法在服务器端实现“读取/处理超时”?任何帮助表示赞赏。

亲切的问候, 迈克尔

【问题讨论】:

    标签: tcp netty


    【解决方案1】:

    ReadTimeoutHandler 添加到管道的第一个位置:

    http://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 躲过了我。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    相关资源
    最近更新 更多