From 182c01b109ffb3b4be248c2e128835ace70eeae8 Mon Sep 17 00:00:00 2001 From: Helius <wangdoubleone@gmail.com> Date: Thu, 27 May 2021 15:53:54 +0800 Subject: [PATCH] add websocket --- src/main/java/com/xcong/excoin/netty/handler/WebSocketServerHandler.java | 21 +++++++++++++++++++-- 1 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/xcong/excoin/netty/handler/WebSocketServerHandler.java b/src/main/java/com/xcong/excoin/netty/handler/WebSocketServerHandler.java index 7b5cd3d..6a70bc2 100644 --- a/src/main/java/com/xcong/excoin/netty/handler/WebSocketServerHandler.java +++ b/src/main/java/com/xcong/excoin/netty/handler/WebSocketServerHandler.java @@ -78,6 +78,7 @@ content = ((TextWebSocketFrame) frame).text(); if (content.contains(Contans.HEART_BEAT)) { resetTimes(ctx.channel()); + ctx.channel().writeAndFlush(NettyTools.webSocketBytes(Contans.HEART_BEAT)); } else { SpringContextHolder.getBean(MsgDispatch.class).webSocketDispatch(ctx, content); } @@ -90,11 +91,27 @@ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { - log.info("[触发器触发]"); +// log.info("[触发器触发]"); if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.READER_IDLE) { - + Integer times = pingTimes.get(ctx.channel().id().asShortText()); + if (times == null) { + times = 0; + } + /*读超时*/ +// log.info("===服务端===({}读超时, {})", ctx.channel().id().asShortText(), times); + // 失败计数器次数大于等于3次的时候,关闭链接,等待client重连 + if (times >= MAX_UN_REC_PING_TIMES) { + log.info("===服务端===(读超时,关闭chanel)"); + // 连续超过N次未收到client的ping消息,那么关闭该通道,等待client重连 + ctx.channel().close(); + } else { + // 失败计数器加1 + times++; + pingTimes.remove(ctx.channel().id().asShortText()); + pingTimes.put(ctx.channel().id().asShortText(), times); + } } else if (event.state() == IdleState.WRITER_IDLE) { /*写超时*/ ctx.channel().writeAndFlush(NettyTools.webSocketBytes(Contans.HEART_BEAT)); -- Gitblit v1.9.1