繁体   English   中英

java bytebuffer 写入读取追加

[英]java bytebuffer write read append

我正在尝试使用 ByteBuffer 来解析作为字节数组接收的数据包流,并且可能包含部分或多个数据包。 数据包的长度可变,所以我需要解析前两个字节来获取数据包长度,似乎一旦我翻转()缓冲区来读取数据包,如果数据包不完整,我就无法返回并附加更多数据。

如何将数据写入缓冲区,读取其中的一些数据以验证内容,然后在保留读取数据的同时在必要时向其中附加更多数据?

class Foo {

    static final byte[] DATA1 = {0, 13, 2, 65, 88, 80, 55, 51, 52, 84, 82, 43, -111};
    static final byte[] DATA2 = {0, 21, 6, 2, 3, 67, 23, 71, -77, 24, -66, -12, -76, 98, 25, 61, 54, -20, 127, -118, 71};
    static final byte[] DATA3 = {0, 21, 5, 3, 5, 67};
    static final byte[] DATA4 = {23, 72, -50, 24, -66, -9, -31, -86, 25, 61, -95, 75, 71, 47, -102, 0, 13, 2, 84};
    static final byte[] DATA5 = {82, 65, 28, 10, 65, 71, 52, 44, 11};

    ByteBuffer mByteBuffer = ByteBuffer.allocate(4096);

    public void test() {
        mByteBuffer.order(ByteOrder.BIG_ENDIAN);
        parse(DATA1);
        parse(DATA2);
        parse(DATA3);
        parse(DATA4);
        parse(DATA5);
    }

    public void parse(byte[] bytes) {
        short byteCount;
        short crc;

        mByteBuffer.put(bytes);
        mByteBuffer.flip();

        while (mByteBuffer.remaining() > 5) {
            byteCount = mByteBuffer.getShort();

            // check for invalid buffer
            if (byteCount < 5) {
                mByteBuffer.clear();
                return;
            }

            if (mByteBuffer.remaining() < (byteCount - 2)) {
                // TODO: incomplete packet, do something
            }

            // payload (u8[1 .. 4092])
            byte[] payload = new byte[byteCount - 4];
            mByteBuffer.get(payload, 0, payload.length);

            // crc (u16)
            crc = mByteBuffer.getShort();
        }

        mByteBuffer.clear();
    }
}

getShort()之后或通常在任何获取或写入序列之后以及下一个read()之前,调用compact() read()

我在这里做了很多更改,所有这些更改都在注释中进行了说明。

private final ByteBuffer mByteBufferAlloc = ByteBuffer.allocate( 4096 );
private ByteBuffer mByteBuffer = mByteBufferAlloc.duplicate(); // create a duplicate so we can use without affecting the original allocated buffer so we have a blank slate to reset to

public void test()
{
    mByteBuffer.order( ByteOrder.BIG_ENDIAN );
    parse( DATA1 );
    parse( DATA2 );
    parse( DATA3 );
    parse( DATA4 );
    parse( DATA5 );
}

public void parse( byte[] bytes )
{
    short byteCount;
    short crc;

    if( bytes.length > mByteBuffer.remaining() ) // Ran out of room, compact anything not yet processed back to the beginning of the buffer and start back with a copy of the allocated buffer
    {
        int numBytes = mByteBuffer.position();
        if( numBytes > 0 )
        {
            byte[] toCompact = new byte[numBytes];
            ((ByteBuffer) mByteBuffer.flip()).get( toCompact );
            mByteBuffer = mByteBufferAlloc.duplicate().put( toCompact );
        }
        else // nothing in the buffer, simply start fresh
            mByteBuffer = mByteBufferAlloc.duplicate();
    }
    mByteBuffer.put( bytes );
    mByteBuffer.flip();

    while( mByteBuffer.remaining() > 5 )
    {
        byteCount = mByteBuffer.getShort();

        // check for invalid buffer
        if( byteCount < 5 )
        {
            System.err.println( "Invalid data, throwing away buffer." );
            mByteBuffer.clear(); // something was invalid, throw away the entire buffer, but we should probably log an error or something
            return;
        }

        if( mByteBuffer.remaining() < (byteCount - 2) )
        {
            // not enough data, wait for more
            break;
        }

        // payload (u8[1 .. 4092])
        byte[] payload = new byte[byteCount - 4];
        mByteBuffer.get( payload, 0, payload.length );

        // crc (u16)
        crc = mByteBuffer.getShort();

        int pos = mByteBuffer.position(), limit = mByteBuffer.limit(), capacity = mByteBuffer.capacity();
        mByteBuffer = ((ByteBuffer) mByteBuffer.limit( capacity )).slice();
        mByteBuffer.limit( limit - pos ); // cut the packet off the beginning so we won't parse it again

        // TODO do something with the packet
    }

    mByteBuffer.position( mByteBuffer.limit() ).limit( mByteBuffer.capacity() ); // reset the position to the end of the added data and the limit to the capacity
    // mByteBuffer.clear(); Don't want to do this because we want the next call to append to the buffer so retain state

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM