第七课 Netty学习之心跳

idleStateHandler

用来检测会话状态

心跳其实就是一个普通的请求,特点数据简单,业务也简单

心跳对于服务端来说,定时清除闲置会话 channelclose(netty3)

心跳对客户端来说,用来检测会话是否断开,是否重连! 用来检测网络延时!


心跳检测简单实例

public class Server {

    public static void main(String[] args) {
        //服务类
                ServerBootstrap bootstrap = new ServerBootstrap();

                //boss线程监听端口,worker线程负责数据读写
                ExecutorService boss = Executors.newCachedThreadPool();
                ExecutorService worker = Executors.newCachedThreadPool();

                //设置niosocket工厂
                bootstrap.setFactory(new NioServerSocketChannelFactory(boss, worker));

                //设置管道的工厂
                bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

                    @Override
                    public ChannelPipeline getPipeline() throws Exception {

                        ChannelPipeline pipeline = Channels.pipeline();
                        //添加超时时间 秒为单位
                        pipeline.addLast("idle", new IdleStateHandler(new HashedWheelTimer(), 5, 5, 10));
                        pipeline.addLast("decoder", new StringDecoder());
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast("helloHandler", new HeartHandler());
                        return pipeline;
                    }
                });

                bootstrap.bind(new InetSocketAddress(8000));

                System.out.println("start!!!");
    }
}

public class HeartHandler extends SimpleChannelHandler {

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
            throws Exception {
           System.out.println(e.getMessage());

           super.messageReceived(ctx, e);
    }

    @Override
    public void handleUpstream(final ChannelHandlerContext ctx, ChannelEvent e)
            throws Exception {
        if (e instanceof IdleStateEvent) {
//读写超时IdleState.ALL_IDLE  读超时 IdleState.READER_IDLE 写超时 IdleState.WRITER_IDLE
            if(((IdleStateEvent)e).getState() == IdleState.ALL_IDLE){
                System.out.println("disconnected ....");
                //关闭会话
                ChannelFuture write = ctx.getChannel().write("time out, you will lose connection");
                write.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                         ctx.getChannel().close();
                    }
                });
            }
        } else {
            super.handleUpstream(ctx, e);
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章