Example #1
0
    public override byte[] toBytes()
    {
        mCmdID       = 2;
        mKeyID       = 1;
        mValueLength = sizeof(byte);
        int payloadLen = sizeof(byte) + sizeof(byte) + sizeof(byte) + mValueLength;

        byte[] payload = new byte[payloadLen];
        int    index   = 0;

        BinaryUtility.writeByte(payload, ref index, mCmdID);
        BinaryUtility.writeByte(payload, ref index, mKeyID);
        BinaryUtility.writeByte(payload, ref index, mValueLength);
        BinaryUtility.writeByte(payload, ref index, mFriction);
        mHeader = new PacketHeader(GameDefine.REPORT_OUT);
        mHeader.mPayloadLength = (ushort)payloadLen;
        mHeader.mCRC16         = BinaryUtility.crc16(0xFF, payload, payloadLen);
        byte[] headerData = mHeader.toBytes();
        byte[] packetData = new byte[payload.Length + headerData.Length];
        BinaryUtility.memcpy(packetData, headerData, 0);
        BinaryUtility.memcpy(packetData, payload, headerData.Length);
        return(packetData);
    }
Example #2
0
    public PARSE_RESULT parseData(byte[] data, int count)
    {
        // 长度不够包头时,数据不足
        if (count < mHeaderLength)
        {
            return(PARSE_RESULT.PR_NOT_ENOUGH);
        }
        // 确保一些固定数值是正确的
        if (data[0] != mReportID || data[1] != mMagicByte || data[2] != mVersion || data[mHeaderLength - 1] != mSeqID)
        {
            UnityUtility.logInfo("data : " + BinaryUtility.bytesToHEXString(data, true, true, count));
            UnityUtility.logInfo("数据错误");
            return(PARSE_RESULT.PR_ERROR);
        }
        int    offset        = sizeof(byte) + sizeof(byte) + sizeof(byte);
        ushort payloadLength = (ushort)BinaryUtility.readShort(data, ref offset, true);

        // 长度不够记录的数据长度,数据不足
        if (payloadLength > count - mHeaderLength)
        {
            return(PARSE_RESULT.PR_NOT_ENOUGH);
        }
        ushort crc = (ushort)BinaryUtility.readShort(data, ref offset, true);
        // 校验失败,数据错误
        ushort dataCRC16 = BinaryUtility.crc16(0xFF, data, payloadLength, mHeaderLength);

        if (crc != dataCRC16)
        {
            UnityUtility.logInfo("校验失败");
            return(PARSE_RESULT.PR_ERROR);
        }
        // 只有解析成功时,才保存数据
        mPayloadLength = payloadLength;
        mCRC16         = crc;
        return(PARSE_RESULT.PR_SUCCESS);
    }