Netty Websocket通讯数据不完整问题原因及处理

原因是浏览器对大数据量请求时,会自动将数据进行分片传输。数据会以ContinuationFrame的形式发送, 直到isFinalFragment为true时结束, 中间不会穿插其它的Frame。

可针对ContinuationFrame的数据进行拼接,得到完整数据后再进行业务操作。

import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;

private StringBuilder frameBuffer = null;
protected void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame)
{

    if (frame instanceof TextWebSocketFrame) {
        frameBuffer = new StringBuilder();
        frameBuffer.append(((TextWebSocketFrame)frame).text());
    }
    else if (frame instanceof ContinuationWebSocketFrame) {
        if (frameBuffer != null) {
            frameBuffer.append(((ContinuationWebSocketFrame)frame).text());
        }
        else {
            logger.warn("Continuation frame received without initial frame.");
        }
    }
    else {
        throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
    }

    // Check if Text or Continuation Frame is final fragment and handle if needed.
    if (frame.isFinalFragment()) {
        handleMessageCompleted(ctx, frameBuffer.toString());
        frameBuffer = null;
    }
}

参考:

https://www.jianshu.com/p/4108e2df3998

https://vimsky.com/examples/detail/java-class-io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame.html

https://ask.csdn.net/questions/757199

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值