2010-09-16 79 views
12

我有一個netty通道,我想在底層套接字上設置一個超時(默認設置爲0)。在netty通道上設置套接字超時

超時的目的是,如果在15分鐘內沒有任何事情發生,未使用的通道將被關閉。

雖然我沒有看到任何配置這樣做,並且套接字本身也對我隱藏。

由於

回答

13

如果使用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)的調用ReadTimeoutException

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