2016-05-17 199 views
0

我有一个关于netty TCP服务器上超时配置的问题。现在,我设置了连接timout这样的:netty - 在TCP服务器上配置超时

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000); 

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

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000); 

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

亲切的问候, 迈克尔

回答

2

添加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()); 
... 
+0

完美啊,不知何故ReadTimeoutHandler躲避我。谢谢。 –