netty服务端实现心跳超时的主动拆链

本文介绍了一个基于Netty的服务器启动示例,并详细展示了如何通过IdleStateHandler和ReadTimeoutHandler来实现读空闲超时处理。此外,还提供了一种更简便的超时处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、服务器启动示例:

public class MySocketServer {
    protected static Logger logger = LoggerFactory.getLogger(MySocketServer.class);

    public void start(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new SocketServerInitializer());

            logger.debug("server side socket start successful on port {}", port);

            b.bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("{}", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

 

二、各种业务Handler:

public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline()
            .addLast(new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS)) // 构造一个超时event消息
            .addLast(new IdleStateTrigger()) // 处理超时event消息
            .addLast(new StringDecoder())
            .addLast(new StringEncoder())
            .addLast(new ServerHandler());
    }
}

 

三、读空闲(超过10s)的事件处理

public class IdleStateTrigger extends ChannelInboundHandlerAdapter {
    protected static Logger logger = LoggerFactory.getLogger(IdleStateTrigger.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            logger.debug("state is {}", state.name());
            if (state == IdleState.READER_IDLE) {
                ctx.close(); // 如果是超过10s没有读到数据,关闭客户端连接
                throw new Exception("idle exception");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

}

 

附录、超时功能的快捷实现
使用自带的ReadTimeoutHandler

public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
         ch.pipeline()
        .addLast(new StringDecoder())
        .addLast(new StringEncoder())
        .addLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS))
        .addLast(new ServerHandler());
    }
}

 

转载于:https://www.cnblogs.com/yoyotl/p/7514836.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值