如何将两个字符串和一个列表<字节[]>聚合成一个字节[],然后提取它们



我需要将2个字符串和一个列表聚合成一个字节[],以便通过网络发送它(使用具有send(byte[])函数的特殊库)。

然后,在另一端,我需要得到3个不同的对象。

我做了一个丑陋的实现,但是它非常慢。基本上,我要做的是

        public byte[] myserializer(String dataA, String dataB, List<byte[]> info) {
        byte[] header = (dataA +";" + dataB + ";").getBytes();
        int numOfBytes = 0;
        for (byte[] bs : info) {
            numOfBytes += bs.length;
        }
        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o;
        try {
            o = new ObjectOutputStream(b);
            o.writeObject(info);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] data = b.toByteArray();
        int length = header.length + data.length;
        byte[] headerLength = (new Integer(header.length)).toString()
                .getBytes();
        byte[] pattern = ";".getBytes();
        int finalLength = headerLength.length + pattern.length + length;
        byte[] total = new byte[finalLength];enter code here
        total = // Copy headerLength, header and total into byte[] total
        return return;

实际上我要创建一个像这样的框架

      HEADER                    INFO

(-----------------------------------------------)(----------------------------------)HEADER_LENGHT; DATA_A DATA_B; SERIALIZED_LIST_OBJECT

然后,在接收端,我执行相反的过程,这就是"全部"。这是有效的,但是它非常低效和丑陋。

建议吗?最佳实践?想法吗?

哦…还有一点:这也必须适用于J2SE和Android

非常感谢!!

将其全部写入ByteArrayOutputStream,并在其周围使用ObjectOutputStream来序列化字符串和列表,然后调用将BAOS转换为byte[]数组的方法。在另一端,做相反的。

或者定义一个包含{String, String, List}元组的可序列化对象,用ObjectOutputStream序列化它,用ObjectInputStream反序列化它。更加简单。

或者只发送三次。TCP是字节流,消息之间没有边界,字节都是顺序到达的。如果您想保留对网络的写入,请插入BufferedOutputStream并在写入List后将其刷新。

下面是一个简单的方法,用于序列化字节数组并在另一端反序列化它。注意,该方法只接受一个类型为List<byte[]>的参数,由于参数dataAdataB的类型为String,因此可以简单地假设列表中的前两个byte[]元素就是这两个参数。我相信这比通过ObjectOutputStream进行对象序列化要快得多,而且在另一端反序列化也会更快。

public class ByteListSerializer {
static private final int INT_SIZE = Integer.SIZE / 8;
    static public void main(String...args) {
        ByteListSerializer bls = new ByteListSerializer();
        // ============== variable declaration =================
        String dataA = "hello";
        String dataB = "world";
        List<byte[]> info = new ArrayList<byte[]>();
        info.add(new byte[] {'s','o','m','e'});
        info.add(new byte[] {'d','a','t','a'});
        // ============= end variable declaration ==============
        // ======== serialization =========
        info.add(0, dataA.getBytes());
        info.add(1, dataB.getBytes());
        byte[] result = bls.dataSerializer(info);
        System.out.println(Arrays.toString(result));
        // ======== deserialization ========
        List<byte[]> back = bls.dataDeserializer(result);
        String backDataA = new String(back.get(0));
        String backDataB = new String(back.get(1));
        back.remove(0);
        back.remove(0);
        // ============ print end result ============
        System.out.println(backDataA);
        System.out.println(backDataB);
        for (byte[] b : back) {
            System.out.println(new String(b));
        }
    }
    public byte[] dataSerializer(List<byte[]> data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteBuffer lenBuffer = ByteBuffer.allocate(4);
        try {
            for (byte[] d : data) {
                lenBuffer.putInt(0, d.length);
                out.write(lenBuffer.array());
                out.write(d);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // wrap this
        byte[] dataBuffer = new byte[out.size() + 4];
        lenBuffer.putInt(0, out.size());
        System.arraycopy(lenBuffer.array(), 0, dataBuffer, 0, 4);
        System.arraycopy(out.toByteArray(), 0, dataBuffer, 4, out.size());
        return dataBuffer;
    }
    public List<byte[]> dataDeserializer(byte[] data) {
        if (data.length < INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }
        ByteBuffer dataBuffer = ByteBuffer.wrap(data);
        int packetSize = dataBuffer.getInt();
        if (packetSize > data.length - INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }
        List<byte[]> dataList = new ArrayList<byte[]>();
        int len, pos = dataBuffer.position(), nextPos;
        while (dataBuffer.hasRemaining() && (packetSize > 0)) {
            len = dataBuffer.getInt();
            pos += INT_SIZE;
            nextPos = pos + len;
            dataList.add(Arrays.copyOfRange(data, pos, nextPos));
            dataBuffer.position(pos = nextPos);
            packetSize -= len;
        }
        return dataList;
    }
}

框架构造为

     - 4 bytes: the total bytes to read (frame size = [nnnn] + 4 bytes header)
    |      - 4 bytes: the first chunk size in bytes
    |     |          - x bytes: the first chunk data
    |     |         |          
    |     |         |           - 4 bytes: the n chunk size in byte
    |     |         |          |         - x bytes: the n chunk data
    |     |         |          |        |
    |     |         |          |        |
[nnnn][iiii][dddd....][...][iiii][dddd...]
上面的例子将输出
[0, 0, 0, 34, 0, 0, 0, 5, 104, 101, 108, 108, 111, 0, 0, 0, 5, 119, 111, 114, 108, 100, 0, 0, 0, 4, 115, 111, 109, 101, 0, 0, 0, 4, 100, 97, 116, 97]
hello
world
some
data

注意框架格式是由byte[]块组成的,所以只要你知道块的顺序,你就可以对几乎任何数据集使用这些方法。

相关内容

最新更新