public static void Run()
    {
        MessageObject protos = read("../../json/rootProtos.json");
        MessageObject msgs   = read("../../json/rootMsg.json");

        Protobuf protobuf = new Protobuf(protos, protos);

        ICollection <string> keys = msgs.Keys;

        foreach (string key in keys)
        {
            MessageObject msg    = (MessageObject)msgs[key];
            byte[]        bytes  = protobuf.encode(key, msg);
            MessageObject result = protobuf.Decode(key, bytes);
            if (!equal(msg, result))
            {
                Console.WriteLine("protobuf test failed!");
                return;
            }
        }

        Console.WriteLine("Protobuf test success!");
    }
예제 #2
0
    public Message Decode(byte[] buffer)
    {
        //Decode head
        //Get flag
        byte flag = buffer[0];
        //Set offset to 1, for the 1st byte will always be the flag
        int offset = 1;

        //Get type from flag;
        enMessageType type = (enMessageType)((flag >> 1) & MSG_Type_Mask);
        uint          id   = 0;
        string        route;

        if (type == enMessageType.Response)
        {
            int length;
            id = (uint)Decoder.DecodeUInt32(offset, buffer, out length);
            if (id <= 0 || !reqMap.ContainsKey(id))
            {
                return(null);
            }
            else
            {
                route = reqMap[id];
                reqMap.Remove(id);
            }

            offset += length;
        }
        else if (type == enMessageType.Push)
        {
            //Get route
            if ((flag & 0x01) == 1)
            {
                ushort routeId = ReadShort(offset, buffer);
                route = abbrs[routeId];

                offset += 2;
            }
            else
            {
                byte length = buffer[offset];
                offset += 1;

                route   = Encoding.UTF8.GetString(buffer, offset, length);
                offset += length;
            }
        }
        else
        {
            return(null);
        }

        //Decode body
        byte[] body = new byte[buffer.Length - offset];
        for (int i = 0; i < body.Length; i++)
        {
            body[i] = buffer[i + offset];
        }

        MessageObject msg;
        string        rawString = null;

        if (decodeProtos.ContainsKey(route))
        {
            msg = protobuf.Decode(route, body);
        }
        else
        {
            rawString = Encoding.UTF8.GetString(body);
            msg       = (MessageObject)SimpleJson.SimpleJson.DeserializeObject(rawString);
        }

        //Construct the message
        return(new Message(type, id, route, msg, rawString));
    }