Netty websocket客户端中的乒乓机制 - 每隔5分钟发送一次ping帧

时间:2018-06-01 15:24:31

标签: netty

我有一个客户端应用程序,它从Websocket服务器接收消息。

如果我必须在每5分钟不活动后对服务器执行一次ping操作,该怎么办? 我正在尝试使用Netty计时器来执行此操作。

    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            Channel ch = ctx.channel();
            WebSocketFrame frame = (WebSocketFrame)msg;
            if ((frame instanceof BinaryWebSocketFrame)) {
                BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame)frame;
                ByteBuf buffer = binaryWebSocketFrame.content();
                byte[] bytes = new byte[buffer.readableBytes()];
                buffer.getBytes(0, bytes);
                String data = new String(bytes, Charset.defaultCharset());
                JsonObject jsonObject = this.jsonParser.parse(data).getAsJsonObject();

                //ch.write(new PingWebSocketFrame()); //How to send ping every 5minutes. Is this the right place to send the ping message?

               //Is the below code a right way to of using the Timer:
                **Timer timer = new Timer() {
                @Override
                public Timeout newTimeout(TimerTask timerTask, long l, TimeUnit timeUnit) {
                    //return null;
                    TimerTask task = timeout -> ch.write(new PingWebSocketFrame(buffer));
                    return newTimeout(task, 5, TimeUnit.MINUTES);
                }
                @Override
                public Set<Timeout> stop() {
                    return null;
                    }
                };
                TimerTask task = timeout -> ch.write(new PingWebSocketFrame(buffer));
                timer.newTimeout(task, 5, TimeUnit.MINUTES);**

            }
            else if ((frame instanceof PingWebSocketFrame)) {
                frame.content().retain();
                ch.writeAndFlush(new PongWebSocketFrame(frame.content()));
                //return;
            }
            else if ((frame instanceof PongWebSocketFrame)) {
                System.out.println("WebSocket Client received pong");
            }
            else if ((frame instanceof CloseWebSocketFrame)) {
                ch.close();
            }
        }

1 个答案:

答案 0 :(得分:1)

您可以使用ctx.executor().schedule(...)。除此之外,您还可以使用IdleStateHandler,如果5分钟内没有活动,则会发出IdleStateEvent。然后你可以拦截这个事件并触发写入。