zoukankan      html  css  js  c++  java
  • netty服务端实现心跳超时的主动拆链

    一、服务器启动示例:

    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());
        }
    }
  • 相关阅读:
    windows10、windows server 2016激活方法
    .NET 和 .NET Core 使用 JWT 授权验证
    vs(vs2017、vs2019)离线安装包下载、制作
    VS顶部增加签名描述信息
    .NET WebAPI 跨域问题(has been blocked by CORS policy:No AccessControlAllowOgigin header is present on the requested resource)
    .Net 和 .Net Core 集成Swagger 以及配合JWT身份验证
    jQuery实现公告无限循环滚动
    甩掉 ashx/asmx,使用jQuery.ajaxWebService请求WebMethod,Ajax处理更加简练(转)
    JS和JQUERY常见函数封装方式
    第07组 Beta冲刺 (1/5)(组长)
  • 原文地址:https://www.cnblogs.com/yoyotl/p/7514836.html
Copyright © 2011-2022 走看看