Example #1
0
        public void Protocol()
        {
            // 构造请求
            var request = new RequestMessage()
            {
                I = 1,
            };
            var roomOptions = new RoomOptions {
                Visible              = false,
                EmptyRoomTtl         = 60,
                MaxPlayerCount       = 2,
                PlayerTtl            = 60,
                CustomRoomProperties = new PlayObject {
                    { "title", "room title" },
                    { "level", 2 },
                },
                CustomRoomPropertyKeysForLobby = new List <string> {
                    "level"
                }
            };
            var expectedUserIds = new List <string> {
                "world"
            };
            var roomOpts = ConvertToRoomOptions("abc", roomOptions, expectedUserIds);

            request.CreateRoom = new CreateRoomRequest {
                RoomOptions = roomOpts
            };
            var command = new Command {
                Cmd  = CommandType.Conv,
                Op   = OpType.Start,
                Body = new Body {
                    Request = request
                }.ToByteString()
            };
            // 序列化请求
            var bytes = command.ToByteArray();
            // 反序列化请求
            var reCommand = Command.Parser.ParseFrom(bytes);

            Assert.AreEqual(reCommand.Cmd, CommandType.Conv);
            Assert.AreEqual(reCommand.Op, OpType.Start);
            var reBody    = Body.Parser.ParseFrom(reCommand.Body);
            var reRequest = reBody.Request;

            Assert.AreEqual(reRequest.I, 1);
            var reRoomOptions = request.CreateRoom.RoomOptions;

            Assert.AreEqual(reRoomOptions.Visible, false);
            Assert.AreEqual(reRoomOptions.EmptyRoomTtl, 60);
            Assert.AreEqual(reRoomOptions.MaxMembers, 2);
            Assert.AreEqual(reRoomOptions.PlayerTtl, 60);
            var attrBytes = reRoomOptions.Attr;
            var reAttr    = CodecUtils.Deserialize(GenericCollectionValue.Parser.ParseFrom(attrBytes)) as PlayObject;

            Debug.Log(reAttr["title"]);
            Debug.Log(reAttr["level"]);
            Assert.AreEqual(reAttr["title"], "room title");
            Assert.AreEqual(reAttr["level"], 2);
        }
Example #2
0
        internal static Protocol.RoomOptions ConvertToRoomOptions(string roomName, RoomOptions options, List <string> expectedUserIds)
        {
            var roomOptions = new Protocol.RoomOptions();

            if (!string.IsNullOrEmpty(roomName))
            {
                roomOptions.Cid = roomName;
            }
            if (options != null)
            {
                roomOptions.Visible      = options.Visible;
                roomOptions.Open         = options.Open;
                roomOptions.EmptyRoomTtl = options.EmptyRoomTtl;
                roomOptions.PlayerTtl    = options.PlayerTtl;
                roomOptions.MaxMembers   = options.MaxPlayerCount;
                roomOptions.Flag         = options.Flag;
                roomOptions.Attr         = CodecUtils.Serialize(options.CustomRoomProperties).ToByteString();
                roomOptions.LobbyAttrKeys.AddRange(options.CustomRoomPropertyKeysForLobby);
            }
            if (expectedUserIds != null)
            {
                roomOptions.ExpectMembers.AddRange(expectedUserIds);
            }
            return(roomOptions);
        }
Example #3
0
        void HandleRoomCustomPropertiesChanged(UpdatePropertyNotification updatePropertyNotification)
        {
            var changedProps = CodecUtils.DeserializePlayObject(updatePropertyNotification.Attr);

            // 房间属性变化
            MergeCustomProperties(changedProps);
            Client.OnRoomCustomPropertiesChanged?.Invoke(changedProps);
        }
Example #4
0
        void HandleSendEvent(DirectCommand directCommand)
        {
            var eventId   = (byte)directCommand.EventId;
            var eventData = CodecUtils.DeserializePlayObject(directCommand.Msg);
            var senderId  = directCommand.FromActorId;

            Client.OnCustomEvent?.Invoke(eventId, eventData, senderId);
        }
Example #5
0
            public static byte[] Serialize(object obj)
            {
                Weapon weapon     = obj as Weapon;
                var    playObject = new PlayObject {
                    { "name", weapon.Name },
                    { "attack", weapon.Attack }
                };

                return(CodecUtils.SerializePlayObject(playObject));
            }
Example #6
0
            public static object Deserialize(byte[] bytes)
            {
                var    playObject = CodecUtils.DeserializePlayObject(bytes);
                Weapon weapon     = new Weapon {
                    Name   = playObject.GetString("name"),
                    Attack = playObject.GetInt("attack")
                };

                return(weapon);
            }
Example #7
0
 internal void Init(Room room, RoomMember playerData)
 {
     Room     = room;
     UserId   = playerData.Pid;
     ActorId  = playerData.ActorId;
     IsActive = !playerData.Inactive;
     if (playerData.Attr != null)
     {
         CustomProperties = CodecUtils.DeserializePlayObject(playerData.Attr);
     }
 }
Example #8
0
            public static object Deserialize(byte[] bytes)
            {
                var  playObject = CodecUtils.DeserializePlayObject(bytes);
                Hero hero       = new Hero {
                    Name    = playObject.GetString("name"),
                    Score   = playObject.GetFloat("score"),
                    Hp      = playObject.GetInt("hp"),
                    Mp      = playObject.GetInt("mp"),
                    Weapons = playObject.GetPlayArray("weapons").ToList <Weapon>()
                };

                return(hero);
            }
Example #9
0
            public static byte[] Serialize(object obj)
            {
                Hero hero       = obj as Hero;
                var  playObject = new PlayObject {
                    { "name", hero.Name },
                    { "score", hero.Score },
                    { "hp", hero.Hp },
                    { "mp", hero.Mp },
                    { "weapons", new PlayArray(hero.Weapons) }
                };

                return(CodecUtils.SerializePlayObject(playObject));
            }
Example #10
0
        void HandlePlayerCustomPropertiesChanged(UpdatePropertyNotification updatePropertyNotification)
        {
            var changedProps = CodecUtils.DeserializePlayObject(updatePropertyNotification.Attr);
            // 玩家属性变化
            var player = GetPlayer(updatePropertyNotification.ActorId);

            if (player == null)
            {
                Logger.Error("No player id: {0} when player properties changed", updatePropertyNotification);
                return;
            }
            player.MergeCustomProperties(changedProps);
            Client.OnPlayerCustomPropertiesChanged?.Invoke(player, changedProps);
        }
Example #11
0
        public void PlayObject()
        {
            var playObj = new PlayObject {
                ["i"]   = 123,
                ["b"]   = true,
                ["str"] = "hello, world"
            };
            var subPlayObj = new PlayObject {
                ["si"]   = 345,
                ["sb"]   = true,
                ["sstr"] = "code"
            };

            playObj.Add("obj", subPlayObj);
            var subPlayArr = new PlayArray {
                666, true, "engineer"
            };

            playObj.Add("arr", subPlayArr);
            var genericValue = CodecUtils.Serialize(playObj);

            Debug.Log(genericValue);
            var newPlayObj = CodecUtils.Deserialize(genericValue) as PlayObject;

            Assert.AreEqual(newPlayObj["i"], 123);
            Assert.AreEqual(newPlayObj["b"], true);
            Assert.AreEqual(newPlayObj["str"], "hello, world");
            var newSubPlayObj = newPlayObj["obj"] as PlayObject;

            Assert.AreEqual(newSubPlayObj["si"], 345);
            Assert.AreEqual(newSubPlayObj["sb"], true);
            Assert.AreEqual(newSubPlayObj["sstr"], "code");
            var newSubPlayArr = newPlayObj["arr"] as PlayArray;

            Assert.AreEqual(newSubPlayArr[0], 666);
            Assert.AreEqual(newSubPlayArr[1], true);
            Assert.AreEqual(newSubPlayArr[2], "engineer");
            // Dictionary to PlayObject
            var dict = new Dictionary <string, int> {
                { "hello", 123 },
                { "world", 456 }
            };
            var dictObj = new PlayObject(dict);

            Assert.AreEqual(dictObj["hello"], 123);
            Assert.AreEqual(dictObj["world"], 456);
        }
Example #12
0
        internal async Task <PlayObject> SetRoomCustomProperties(PlayObject properties, PlayObject expectedValues)
        {
            var request = NewRequest();

            request.UpdateProperty = new UpdatePropertyRequest {
                Attr = ByteString.CopyFrom(CodecUtils.SerializePlayObject(properties))
            };
            if (expectedValues != null)
            {
                request.UpdateProperty.ExpectAttr = ByteString.CopyFrom(CodecUtils.SerializePlayObject(expectedValues));
            }
            var res = await SendRequest(CommandType.Conv, OpType.Update, request);

            var props = CodecUtils.DeserializePlayObject(res.Response.UpdateProperty.Attr);

            return(props);
        }
Example #13
0
        internal async Task <Tuple <int, PlayObject> > SetPlayerCustomProperties(int playerId, PlayObject properties, PlayObject expectedValues)
        {
            var request = NewRequest();

            request.UpdateProperty = new UpdatePropertyRequest {
                TargetActorId = playerId,
                Attr          = ByteString.CopyFrom(CodecUtils.SerializePlayObject(properties))
            };
            if (expectedValues != null)
            {
                request.UpdateProperty.ExpectAttr = ByteString.CopyFrom(CodecUtils.SerializePlayObject(expectedValues));
            }
            var res = await SendRequest(CommandType.Conv, OpType.UpdatePlayerProp, request);

            var actorId = res.Response.UpdateProperty.ActorId;
            var props   = CodecUtils.DeserializePlayObject(res.Response.UpdateProperty.Attr);

            return(new Tuple <int, PlayObject>(actorId, props));
        }
Example #14
0
        internal Task SendEvent(byte eventId, PlayObject eventData, SendEventOptions options)
        {
            var direct = new DirectCommand {
                EventId = eventId
            };

            if (eventData != null)
            {
                direct.Msg = ByteString.CopyFrom(CodecUtils.SerializePlayObject(eventData));
            }
            direct.ReceiverGroup = (int)options.ReceiverGroup;
            if (options.TargetActorIds != null)
            {
                direct.ToActorIds.AddRange(options.TargetActorIds);
            }
            _ = Send(CommandType.Direct, OpType.None, new Body {
                Direct = direct
            });
            return(Task.FromResult(true));
        }
Example #15
0
        LobbyRoom ConvertToLobbyRoom(Protocol.RoomOptions options)
        {
            var lobbyRoom = new LobbyRoom {
                RoomName       = options.Cid,
                Open           = options.Open == null || options.Open.Value,
                Visible        = options.Visible == null || options.Visible.Value,
                MaxPlayerCount = options.MaxMembers,
                PlayerCount    = options.MemberCount,
                EmptyRoomTtl   = options.EmptyRoomTtl,
                PlayerTtl      = options.PlayerTtl
            };

            if (options.ExpectMembers != null)
            {
                lobbyRoom.ExpectedUserIds = options.ExpectMembers.ToList <string>();
            }
            if (options.Attr != null)
            {
                lobbyRoom.CustomRoomProperties = CodecUtils.DeserializePlayObject(options.Attr);
            }
            return(lobbyRoom);
        }
Example #16
0
        public void PlayArray()
        {
            var playArr = new PlayArray {
                123, true, "hello, world",
                new PlayObject {
                    ["i"]   = 23,
                    ["b"]   = true,
                    ["str"] = "hello"
                }
            };
            var genericValue = CodecUtils.Serialize(playArr);

            Debug.Log(genericValue);
            var newPlayArr = CodecUtils.Deserialize(genericValue) as PlayArray;

            Assert.AreEqual(newPlayArr[0], 123);
            Assert.AreEqual(newPlayArr[1], true);
            Assert.AreEqual(newPlayArr[2], "hello, world");
            var subPlayObj = newPlayArr[3] as PlayObject;

            Assert.AreEqual(subPlayObj["i"], 23);
            Assert.AreEqual(subPlayObj["b"], true);
            Assert.AreEqual(subPlayObj["str"], "hello");
            // List to PlayArray
            var iList = new List <int> {
                10, 24
            };
            var iArr = new PlayArray(iList);

            Assert.AreEqual(iArr[0], 10);
            Assert.AreEqual(iArr[1], 24);
            var sList = new List <string> {
                "hello", "world"
            };
            var sArr = new PlayArray(sList);

            Assert.AreEqual(sArr[0], "hello");
            Assert.AreEqual(sArr[1], "world");
        }
Example #17
0
        public void CustomType()
        {
            CodecUtils.RegisterType(typeof(Hero), 10, Hero.Serialize, Hero.Deserialize);
            CodecUtils.RegisterType(typeof(Weapon), 11, Weapon.Serialize, Weapon.Deserialize);
            var hero = new Hero {
                Name    = "Li Lei",
                Score   = 99.9f,
                Hp      = 10,
                Mp      = 8,
                Weapons = new List <Weapon> {
                    new Weapon {
                        Name   = "pen",
                        Attack = 100
                    },
                    new Weapon {
                        Name   = "erase",
                        Attack = 200
                    }
                }
            };
            var data    = CodecUtils.Serialize(hero);
            var newHero = CodecUtils.Deserialize(data) as Hero;

            Assert.AreEqual(newHero.Name, "Li Lei");
            Assert.AreEqual(Math.Abs(newHero.Score - 99.9f) < float.Epsilon, true);
            Assert.AreEqual(newHero.Hp, 10);
            Assert.AreEqual(newHero.Mp, 8);
            var pen = newHero.Weapons[0];

            Assert.AreEqual(pen.Name, "pen");
            Assert.AreEqual(pen.Attack, 100);
            var erase = newHero.Weapons[1];

            Assert.AreEqual(erase.Name, "erase");
            Assert.AreEqual(erase.Attack, 200);
        }
Example #18
0
        void Init(Protocol.RoomOptions options)
        {
            Name            = options.Cid;
            Open            = options.Open == null || options.Open.Value;
            Visible         = options.Visible == null || options.Visible.Value;
            MaxPlayerCount  = options.MaxMembers;
            MasterActorId   = options.MasterActorId;
            ExpectedUserIds = new List <string>();
            if (options.ExpectMembers != null)
            {
                ExpectedUserIds.AddRange(options.ExpectMembers);
            }
            playerDict = new Dictionary <int, Player>();
            foreach (RoomMember member in options.Members)
            {
                Player player = new Player();
                player.Init(this, member);
                if (player.UserId == Client.UserId)
                {
                    Player = player;
                }
                playerDict.Add(player.ActorId, player);
            }
            // attr
            CustomProperties    = CodecUtils.DeserializePlayObject(options.Attr);
            gameConn.OnMessage += (cmd, op, body) => {
                switch (cmd)
                {
                case CommandType.Conv:
                    switch (op)
                    {
                    case OpType.MembersJoined:
                        HandlePlayerJoinedRoom(body.RoomNotification.JoinRoom);
                        break;

                    case OpType.MembersLeft:
                        HandlePlayerLeftRoom(body.RoomNotification.LeftRoom);
                        break;

                    case OpType.MasterClientChanged:
                        HandleMasterChanged(body.RoomNotification.UpdateMasterClient);
                        break;

                    case OpType.SystemPropertyUpdatedNotify:
                        HandleRoomSystemPropertiesChanged(body.RoomNotification.UpdateSysProperty);
                        break;

                    case OpType.UpdatedNotify:
                        HandleRoomCustomPropertiesChanged(body.RoomNotification.UpdateProperty);
                        break;

                    case OpType.PlayerProps:
                        HandlePlayerCustomPropertiesChanged(body.RoomNotification.UpdateProperty);
                        break;

                    case OpType.MembersOffline:
                        HandlePlayerOffline(body.RoomNotification);
                        break;

                    case OpType.MembersOnline:
                        HandlePlayerOnline(body.RoomNotification);
                        break;

                    case OpType.KickedNotice:
                        HandleRoomKicked(body.RoomNotification);
                        break;

                    default:
                        Logger.Error("unknown msg: {0}/{1} {2}", cmd, op, body);
                        break;
                    }
                    break;

                case CommandType.Events:
                    break;

                case CommandType.Direct:
                    HandleSendEvent(body.Direct);
                    break;

                case CommandType.Error: {
                    Logger.Error("error msg: {0}", body);
                    ErrorInfo errorInfo = body.Error.ErrorInfo;
                    Client.OnError?.Invoke(errorInfo.ReasonCode, errorInfo.Detail);
                }
                break;

                default:
                    Logger.Error("unknown msg: {0}/{1} {2}", cmd, op, body);
                    break;
                }
            };
            gameConn.OnClose += (code, message) => {
                Client.OnDisconnected?.Invoke();
            };
        }