首页  

netty空闲连接检测     所属分类 netty 浏览量 63
增加 IdleStateHandler  统计连接空闲状态

IdleStateHandler(boolean observeOutput,long readerIdleTime, long writerIdleTime, long allIdleTime,TimeUnit unit)

@Override
public void initChannel(SocketChannel ch) {
     ChannelPipeline p = ch.pipeline();
     p.addLast(new IdleStateHandler(5, 7, 20,TimeUnit.SECONDS));
     p.addLast(new IdleEchoServerHandler());
}
                 
                          
observeOutput
whether or not the consumption of bytes should be taken into consideration when assessing write idleness. The default is  false.
     
     
超过指定时间没有读写的连接会触发 IdleStateEvent
重写 userEventTriggered 方法 ,收到 IdleStateEvent  关闭 空闲连接

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
			System.out.println(ctx.channel().remoteAddress() + " closed ,idleStateEvent=" + idleStateEvent);
			ctx.channel().close();
		}
	}
	
public enum IdleState {
    /**
     * No data was received for a while.
     */
    READER_IDLE,
    /**
     * No data was sent for a while.
     */
    WRITER_IDLE,
    /**
     * No data was either received or sent for a while.
     */
    ALL_IDLE
}


IdleStateHandler 原理 long lastReadTime; long lastWriteTime; initialize(ChannelHandlerContext ctx) schedule(ctx, new ReaderIdleTimeoutTask(ctx),readerIdleTimeNanos, TimeUnit.NANOSECONDS); schedule(ChannelHandlerContext ctx, Runnable task, long delay, TimeUnit unit) { return ctx.executor().schedule(task, delay, unit); } WriterIdleTimeoutTask AllIdleTimeoutTask protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception { ctx.fireUserEventTriggered(evt); }
telnet 上去之后 ,不做任何操作 ,连接会被关闭 telnet 127.0.0.1 6789 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host. 服务端输出 2020-04-15T18:56:21.750 schannelActive ,remoteAddress=/127.0.0.1:64894,eventLoop=io.netty.channel.nio.NioEventLoop@3abfe836 2020-04-15T18:56:26.741 /127.0.0.1:64894 closed ,idleStateEvent=READER_IDLE 完整代码 https://gitee.com/dyyx/netty4demo/tree/master/src/main/java/dyyx/idle

上一篇     下一篇
vert.x介绍

基于netty实例演示NIO BIO 异步和同步

netty读写流量统计实例

netty 服务端启动日志

springboot应用安全防护

netty ChannelFuture 实例