小编Lan*_*Lan的帖子

在netty中发送两个字节缓冲区(标头+正文)的最佳方法

在netty中发送两个字节缓冲区(标头+主体)的最佳方法是什么

我在我们的项目中使用netty,现在我们将以以下格式发送数据

  1. header:int(32bit),包含body的长度
  2. 正文:字节[]

我正在寻找发送 header+body 最快的最佳方法,重点是我想避免数组复制,因为主体有大量数据。

1)创建一个新的byte[]并将body复制到其中

void sendData1(ChannelHandlerContext ctx, byte[] body) {
    byte[] newBuf = new byte[4+body.length];

    // header
    int len = body.length;
    newBuf[3] = (byte) (len & 0xff);
    len >>= 8;
    newBuf[2] = (byte) (len & 0xff);
    len >>= 8;
    newBuf[1] = (byte) (len & 0xff);
    len >>= 8;
    newBuf[0] = (byte) len;

    // body
    System.arraycopy(body, 0, newBuf, 4, body.length);

    final ByteBuf outBuf = Unpooled.wrappedBuffer(newBuf);
    ctx.writeAndFlush(outBuf);
}
Run Code Online (Sandbox Code Playgroud)

2)直接使用netty ByteBuf的write函数

void sendData2(ChannelHandlerContext ctx, byte[] body) {
    final ByteBuf …
Run Code Online (Sandbox Code Playgroud)

netty

5
推荐指数
1
解决办法
2507
查看次数

标签 统计

netty ×1