赞
踩
这里就需要提到一个netty重要的
IdleStateHandler
,用于处理心跳机制;为当前连接通道设置 读、写、读写 空闲超时时间,当达到了设定的时间那么就会回调ClientHandler
中的userEventTriggered(ChannelHandlerContext ctx, Object evt)
函数。
这里在解释一下什么叫空闲超时:假设你设置了客户端读超时为10s,如果持续10s内客户端没有收到数据(也就是服务端没有发送数据过来)那么就会回调userEventTriggered
函数,如果有一直收到数据那么就不会回调userEventTriggered
函数;直到持续10s没有收到数据则继续触发userEventTriggered
函数。
IdleStateHandler()
常用的构造函数,三个参数的释义
- 1public IdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
- 2 this((long)readerIdleTimeSeconds, (long)writerIdleTimeSeconds, (long)allIdleTimeSeconds, TimeUnit.SECONDS);
- 3 }
readerIdleTimeSeconds 空闲读的时长
writerIdleTimeSeconds 空闲写的时长
writerIdleTimeSeconds 空闲读写的时长
与之前添加编解码器一样,往ChannelPipeline
添加即可
- 1NioEventLoopGroup group = new NioEventLoopGroup();
- 2Bootstrap bootstrap = new Bootstrap()
- 3 // 省略部分代码
- 4 .handler(new ChannelInitializer<SocketChannel>() {
- 5 @Override
- 6 protected void initChannel(SocketChannel socketChannel) throws Exception {
- 7 ChannelPipeline pipeline = socketChannel.pipeline();
- 8 //添加心跳处理Handler
- 9 pipeline.addLast(new IdleStateHandler(10, 0, 0));
- 10 //省略部分代码
- 11 }
- 12 });
- 13// 连接到服务端
- 14ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(IP, PORT));
ClientHandler
中进行心跳数据包发送
- 1@Override
- 2public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
- 3 super.userEventTriggered(ctx, evt);
- 4 if (evt instanceof IdleStateEvent) {
- 5 if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
- 6 sendHeartPkg(ctx);
- 7 }
- 8 } else {
- 9 super.userEventTriggered(ctx, evt);
- 10 }
- 11}
- 12/**
- 13 * 发送心跳
- 14 */
- 15private void sendHeartPkg(ChannelHandlerContext ctx) {
- 16 PkgDataBean bean = new PkgDataBean();
- 17 bean.setCmd((byte) 0x02);
- 1

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。