[英]Do I have to set buffer sizes accordingly to the size of the payload in netty?
我阅读了 .netty 4.1 的 .netty.io 教程和 GitHub 的 object 回显示例,但是当发送大小不同的对象时,他们没有 go 详细介绍缓冲区大小。
假设我要发送一个包含一个 int[] 和一个 float[] 的 object。 它是一个 DTO,所以它只是构造函数和吸气剂。
我如何决定缓冲区大小? 我似乎找不到任何答案,所以我认为这是一个愚蠢的问题。 但是要谷歌什么来了解我在这方面的进展呢? 总的来说,我对.networking 还很陌生。
我知道我需要将解码器和编码器处理程序添加到各自的通道管道,但我不知道如何在考虑不同大小的对象的情况下实现它们。 我知道 ObjectDecoder 和 ObjectEncoder 类,但我不知道我应该使缓冲区有多大,因为 DTO 中的 arrays 是动态创建的。
通常序列化一个数组的方式是先记录数组的长度,然后一个一个的序列化 不知道你是不是想问这个,希望对你有帮助
package com.ljy.netty.codec;
import java.util.Arrays;
/**
* Using big-endian byte ordering, reference to the Bits class of the java library
*/
public class IntArrayCodecExample {
public static byte[] encode(int[] ia) {
byte[] bytes = new byte[ia.length * 4 + 4];
writeInt(bytes, 0, ia.length);
for (int i = 0; i < ia.length; i++) {
writeInt(bytes, (i + 1) * 4, ia[i]);
}
return bytes;
}
public static int[] decode(byte[] bytes) {
int length = readInt(bytes, 0);
int[] ia = new int[length];
int offset = 4;
while(offset < bytes.length) {
ia[offset / 4 - 1] = readInt(bytes, offset);
offset += 4;
}
return ia;
}
private static void writeInt(byte[] bytes, int offset, int val) {
bytes[offset + 3] = (byte) (val );
bytes[offset + 2] = (byte) (val >>> 8);
bytes[offset + 1] = (byte) (val >>> 16);
bytes[offset ] = (byte) (val >>> 24);
}
private static int readInt(byte[] b, int off) {
return ((b[off + 3] & 0xFF) ) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off ] ) << 24);
}
public static void main(String[] args) {
int[] ia = new int[]{1, 3, 2, 4, 5};
System.out.println(Arrays.toString(decode(encode(ia))));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.