java协议实现头长度

时间:2018-02-02 12:44:17

标签: java binary network-protocols

如何从Java中的InputStream读取以下数据?或者如何从给定的标题中正确计算长度?

enter image description here

header[0] = 1且header[1] = -7. header[]byte数组时,我的实施似乎不起作用

int length = (header[0] & 0xFF) + (header[1] & 0xFF);

如果上述示例length250

1 个答案:

答案 0 :(得分:1)

两个字节数字的字节顺序(最重要的字节)是不规则的:aLength和crc16。另外我不确定aLength是n还是n - 2 - 7.

void read(InputStream inputStream) throws IOException {
    try (DataInputStream in = new DataInputStream(inputStream)) {
        byte b = in.readByte();
        if (b != 0x02) {
            throw new IOException("First byte must be STX");
        }
        int aLength = in.readUnsignedShort();
        byte[] message = new byte[aLength - 3]; // aLength == n
        in.readFully(message);

        byte comAdr = message[0];
        byte controlByte = message[1];
        byte status = message[2];
        byte[] data = Arrays.copyOfRange(message, 7 - 3, aLength - 2);
        int crc16 = ((message[aLength - 1] << 8) 
& 0xFF) | (message[aLength - 1] & 0xFF);

        // Alternatively a ByteBuffer may come in handy.
        int crc16 = ByteBuffer.wrap(message)
            .order(ByteOrder.LITTLE_ENDIAN)
            .getShort(aLength - 2) & 0xFF;
        ...
        String s = new String(data, StandardCharsets.UTF_8);
    }
}

它首先读取三个字节,这应该始终是可能的(对于其他更短的消息也不应该阻塞)。