netty 半包处理

38 阅读1分钟

添加解码器

pipeline.addLast(new LengthFieldBasedFrameDecoder(
        1024 * 1024,  // 最大帧长度
        0,     // 长度字段偏移量
        4,     // 长度字段字节数
        0,     // 长度调整值
        4      // 初始字节丢弃数
));

消息发送

 ByteBuf buf = Unpooled;
 byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8);
 buf.writeInt(bytes.length);
 buf.write(bytes);
 channel().writeAndFlush(buf);

参数设置错误或者消息未填充长度域 导致 解码失败 且 后续无法读取消息

image.png