网络I/o编程模型17 netty框架实现心跳机制

本文介绍了Netty中的IdleStateHandler处理器,用于处理空闲状态,包括readerIdleTime、writeIdleTime和allIdleTime三个参数,分别对应读、写和读写空闲时触发心跳检测的时间。通过示例代码展示了如何在服务端和自定义处理器中配置和处理心跳事件,以保持连接活跃并检测异常。
摘要由CSDN通过智能技术生成

一 心跳机制说明

IdleStateHandler 是netty提供的处理空闲状态的处理器
long readerIdleTime: 表示多长时间没有读,就会发送一个心跳, 检测包检测是否连接。
long writeIdleTime: 表示多长时间没有写,就会发送一个心跳, 检测包检测是否连接。
long allIdleTime: 表示多长时间没有写,就会发送一个心跳,  检测包检测是否连接。
当IdleStateEvent触发后,就会传递给管道的下一个handler去处理。

二  代码案例

1.server代码

package com.ljf.netty.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.awt.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: NettyHeartheatServer
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/04 15:00:18
 * @Version: V1.0
 **/
public class NettyHeartheatServer {
    public static void main(String[] args) {
        //创建两个线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();//8个NioEventLoop
        try {
        ServerBootstrap serverBootstrap=new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline=ch.pipeline();
                /*
                         IdleStateHandler 是netty提供的处理空闲状态的处理器
                         long readerIdleTime: 表示多长时间没有读,就会发送一个心跳, 检测包检测是否连接。
                         long writeIdleTime: 表示多长时间没有写,就会发送一个心跳, 检测包检测是否连接。
                         long allIdleTime: 表示多长时间没有写,就会发送一个心跳,  检测包检测是否连接。
                         当IdleStateEvent触发后,就会传递给管道的下一个handler去处理。
                */
                pipeline.addLast(new IdleStateHandler(13,5,2, TimeUnit.SECONDS));
                //加入一个对空闲检测进一步处理的handler();
                pipeline.addLast(new MyServerHandler());
            }
        });
        //启动服务器
        ChannelFuture  channelFuture = serverBootstrap.bind(6666).sync();
        channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

2. handler代码

package com.ljf.netty.netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @ClassName: MyServerHandler
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/04 15:29:12
 * @Version: V1.0
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {
    public void userEventTriggered(ChannelHandlerContext ctx, Object msg){
        if(msg instanceof IdleStateEvent){
            IdleStateEvent evnet=(IdleStateEvent)msg;
            String eventType=null;
            switch(evnet.state()){
                case READER_IDLE:
                    eventType="读空闲";
                    break;
                case WRITER_IDLE:
                    eventType="写空闲";
                    break;
                case ALL_IDLE:
                    eventType="读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress()+"------超时时间----------"+eventType);
            System.out.println("服务器做响应处理...");
            //如果发生空闲,我们关闭通道
           // ctx.channel().close();
        }
    }
}

3.测试:

启动服务端

 2.启动客户端

 4.测试

1.将自定义handler中:ctx.channel().close() 代码注释掉

 2.服务端:响应一次,后面就不再进行响应了。

 3.客户端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值