第七課 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);
        }
    }

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