标签:ali hand 服务器端 div inbound seconds write tla writer
netty可支持空闲检测的处理器,用于心态检测,当服务器端超出等待时间,没发生事件时,会触发handler中的方法 userEventTriggered。
1 import io.netty.channel.ChannelInitializer; 2 import io.netty.channel.ChannelPipeline; 3 import io.netty.channel.socket.SocketChannel; 4 import io.netty.handler.timeout.IdleStateHandler; 5 6 import java.util.concurrent.TimeUnit; 7 8 public class MyServerInitlalizer extends ChannelInitializer<SocketChannel> { 9 @Override 10 protected void initChannel(SocketChannel ch) throws Exception { 11 ChannelPipeline pipeline = ch.pipeline(); 12 13 //空闲事件处理器 读空闲5s 写空闲3s 读写空闲7s 14 pipeline.addLast(new IdleStateHandler(5,7,3,TimeUnit.SECONDS)); //空闲检测 在一定时间间隔内 没有读写 15 pipeline.addLast(new MyServerHandler());//自定义的空闲事件处理器 16 17 } 18 }
1 import io.netty.channel.ChannelHandlerContext; 2 import io.netty.channel.ChannelInboundHandler; 3 import io.netty.channel.ChannelInboundHandlerAdapter; 4 import io.netty.channel.SimpleChannelInboundHandler; 5 import io.netty.handler.timeout.IdleStateEvent; 6 7 public class MyServerHandler extends ChannelInboundHandlerAdapter { 8 @Override 9 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 10 //super.userEventTriggered(ctx, evt); 11 if ( evt instanceof IdleStateEvent) {//如果是一个空闲状态 12 IdleStateEvent event = (IdleStateEvent) evt; 13 14 String eventType = null; 15 16 switch (event.state()){ 17 case READER_IDLE: 18 eventType = "读空闲"; 19 break; 20 case WRITER_IDLE: 21 eventType = "写空闲"; 22 break; 23 case ALL_IDLE: 24 eventType = "读写空闲"; 25 break; 26 } 27 28 System.out.println(ctx.channel().remoteAddress() + "超时事件: " + eventType); 29 30 ctx.channel().close(); 31 } 32 } 33 }
标签:ali hand 服务器端 div inbound seconds write tla writer
原文地址:https://www.cnblogs.com/amibandoufu/p/11442823.html