簡體   English   中英

我是否必須根據有效載荷 in.netty 的大小來設置緩沖區大小?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM