在指定的间期内,客户端与服务端的连接是否正常,是否有相关的请求发生
package xss.netty.idle;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* 会话状态的监测
*/
public class IdelServer {
public static void main(String[] args) throws Exception {
//服务启动类
ServerBootstrap bootstrap=new ServerBootstrap();
//两个工作线程池
Executor bossExecutor = Executors.newCachedThreadPool();//boss 线程池工作组
Executor workerExecutor=Executors.newCachedThreadPool();//work线程池工作组
//设置factory
bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor,workerExecutor));
//链接缓冲池的大小
bootstrap.setOption("backlog",1024);
//维持链接的活跃
bootstrap.setOption("tcpNoDelay",true);
//关闭延迟发送
bootstrap.setOption("keepAlive",true);
final Timer timer= new HashedWheelTimer();
//设置管道过滤器工厂
bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline channelPipeline= Channels.pipeline();
//类似监听客户端连接的读写请求事件
channelPipeline.addLast("idleHandler",new IdleStateHandler(timer,6,6,10));
//将输出参数转换为String对象输出到下一个pipe
channelPipeline.addLast("decoder",new StringDecoder());
channelPipeline.addLast("encoder",new StringEncoder());
//业务处理的过滤器类
// channelPipeline.addLast("idleCustomHandler",new IdleCustomHandler());
channelPipeline.addLast("idleCustomHandler",new IdleCustom2Handler());
return channelPipeline;
}
});
//绑定端口
bootstrap.bind(new InetSocketAddress(9999));
System.out.println("Server started...");
}
}
Handle处理器:
package xss.netty.idle;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
/**
* 有三种状态:
* IdleState.ALL_IDLE; 读与写的请求都没有
IdleState.READER_IDLE; 客户端请求服务
IdleState.WRITER_IDLE 服务端回应客户端
*/
public class IdleCustomHandler extends IdleStateAwareChannelHandler implements ChannelHandler {
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
System.out.println("事件状态:" + e.getState());
//super.channelIdle(ctx, e);
}
}