【问题标题】:How to handle PING/PONG frame in Netty 4?如何在 Netty 4 中处理 PING/PONG 帧?
【发布时间】:2019-01-07 01:42:36
【问题描述】:
class ClientWebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

  @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

    }
}

我只能在channelRead0 中接收TextWebSocketFrameBinaryWebSocketFrame

PingWebSocketFramePongWebSocketFrame怎么处理,我想知道客户端什么时候发Ping/Pong

【问题讨论】:

    标签: netty


    【解决方案1】:

    像这样: (知道当时 channelRead0 已被弃用,应该在 5.0 版本之后被删除或不支持,如果您想要最新的答案,请在评论中询问)

    /**
     * * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            l.error("WebSocket Client connected!");
            handshakeFuture.setSuccess();
            return;
        }
    
        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content="
                + response.content().toString(CharsetUtil.UTF_8) + ')');
        }
    
    
        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            l.info("WebSocket Client received message:{} ", textFrame.text());
    
            //needed if the server close the socket if no ping send for long
            //better to send the ping with a timer
            // it allwos to choose the rate
            ch.write(new PingWebSocketFrame());
    
        } else if (frame instanceof PongWebSocketFrame) {
            l.info("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            l.info("WebSocket Client received closing");
            ch.close();
        }
    }
    

    【讨论】:

    • 如何用定时器发送 ping?
    • 尝试将您的 channel.write 包含在这样的计时器中:``` public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ... this.timerLocal.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { Channel ch = ctx.getChannel(); ch.write("data data data"); } }, 25, TimeUnit.SECONDS); ... } ``` stackoverflow.com/questions/8934449/…
    【解决方案2】:

    在任何 WebSocketFrame 到达您的 SimpleChannelInboundHandler 之前,Netty 已经接收到 PingWebSocketFrame 和 PongWebSocketFrame。有关其处理逻辑,请参阅摘要 WebSocketProtocolHandler

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 2021-01-13
      • 2020-01-07
      • 2015-09-06
      • 1970-01-01
      • 2019-03-16
      • 2020-12-29
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多