Пример #1
0
 public void TestAdd()
 {
     serverSyncDictionary.Add(4, "yay");
     SerializeDeltaTo(serverSyncDictionary, clientSyncDictionary);
     Assert.That(clientSyncDictionary.ContainsKey(4));
     Assert.That(clientSyncDictionary[4], Is.EqualTo("yay"));
 }
        // For the SyncDictionary to properly fire the update callback, we must
        // wait a frame before adding the players to the already spawned MatchController
        IEnumerator AddPlayersToMatchController()
        {
            yield return(null);

            matchPlayerData.Add(player1, new MatchPlayerData {
                playerIndex = CanvasController.playerInfos[player1.connectionToClient].playerIndex
            });
            matchPlayerData.Add(player2, new MatchPlayerData {
                playerIndex = CanvasController.playerInfos[player2.connectionToClient].playerIndex
            });
        }
Пример #3
0
        public void ObjectCanBeReusedAfterReset()
        {
            clientSyncDictionary.Reset();

            // make old client the host
            SyncDictionary <int, string> hostList    = clientSyncDictionary;
            SyncDictionary <int, string> clientList2 = new SyncDictionary <int, string>();

            Assert.That(hostList.IsReadOnly, Is.False);

            // Check Add and Sync without errors
            hostList.Add(30, "hello");
            hostList.Add(35, "world");
            SerializeDeltaTo(hostList, clientList2);
        }
Пример #4
0
 private void PopulateSectorIntensitieswithZero()
 {
     for (int i = 0; i < 8; i++)
     {
         sectorIntensities.Add(i, 0);
     }
 }
Пример #5
0
 //Send new player info to server (to add to dict)
 private void CmdPlayerConnect(string name)
 {
     PlayerList.Add(playerId, new Player {
         name = name, score = 0
     });
     playerId++;
 }
Пример #6
0
        private static void Analyze(FileInfo sFileName)
        {
            try
            {
                Assembly asm = Assembly.LoadFile(sFileName.FullName);

                if (asm != null)
                {
                    List <Type> lTypes = GetTypeList <ILineProvider>(asm);

                    m_logger.InfoFormat("Analyzing assembly {0} ({1})", asm.FullName, sFileName);

                    foreach (Type t in lTypes)
                    {
                        try
                        {
                            ILineProvider provider = Activator.CreateInstance(t) as ILineProvider;
                            ExcpHelper.ThrowIf(string.IsNullOrEmpty(provider.UniqueName), "Cannot create provider instance of type {0} from dll '{1}'. Unique Name is empty", t, sFileName);
                            m_diProviders.Add(provider.UniqueName, provider);
                        }
                        catch (Exception excp)
                        {
                            m_logger.Excp(excp, "Cannot create provider instance of type {0} from dll '{1}'", t, sFileName);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                m_logger.Excp(excp, "Cannot get provider(s) from dll '{0}'", sFileName);
            }
        }
Пример #7
0
        public void Run()
        {
            IsWatch = true;

            FileInfo[] fileInfos = GetFileInfos(_path);
            for (int i = 0; i < fileInfos.Length; i++)
            {
                _fileDic.Add(fileInfos[i].FullName, GetFileHash(fileInfos[i].FullName));
            }

            _thread = new Thread(Watcher)
            {
                IsBackground = true
            };

            _thread.Start();
        }
Пример #8
0
        private static void ProcessEvent(eAction action, DelegateThread dt, ThreadContext tc)
        {
            if (dt != null)
            {
                lock (m_oLocker)
                {
                    switch (action)
                    {
                    case eAction.Started:

                        ExcpHelper.ThrowIf(m_diIdToContext.ContainsKey(tc.ManagedThreadId), "Thread is running already {0}", tc);
                        ExcpHelper.ThrowIf(m_diNameToContext.ContainsKey(tc.ThreadName), "Thread is running already {0}", tc);

                        m_diIdToContext.Add(tc.ManagedThreadId, tc);
                        m_diNameToContext.Add(tc.ThreadName, tc);

                        Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count);

                        break;

                    case eAction.Completed:

                        ExcpHelper.ThrowIf(!m_diIdToContext.ContainsKey(tc.ManagedThreadId), "Thread is not running {0}", tc);
                        ExcpHelper.ThrowIf(!m_diNameToContext.ContainsKey(tc.ThreadName), "Thread is not running {0}", tc);

                        m_diIdToContext.Remove(tc.ManagedThreadId);
                        m_diNameToContext.Remove(tc.ThreadName);

                        Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count);

                        break;

                    case eAction.Error:


                        Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count);
                        break;

                    default:

                        Debug.Assert(false);
                        break;
                    }

                    try
                    {
                        if (dt != null)
                        {
                            dt(tc);
                        }
                    }
                    catch (Exception excp)
                    {
                        m_logger.Error(ExcpHelper.FormatException(excp, "ProcessEvent {0} ERROR for {1}:\r\n{2}\r\n{3}", action, tc, excp.Message, excp.StackTrace), excp);
                    }
                }
            }
        }
Пример #9
0
        public void SetUp()
        {
            serverSyncDictionary = new SyncDictionary <int, string>();
            clientSyncDictionary = new SyncDictionary <int, string>();

            // add some data to the list
            serverSyncDictionary.Add(0, "Hello");
            serverSyncDictionary.Add(1, "World");
            serverSyncDictionary.Add(2, "!");
            SerializeAllTo(serverSyncDictionary, clientSyncDictionary);

            // set up dirty callbacks for testing.
            // AFTER adding the example data. we already know we added that data.
            serverSyncDictionaryDirtyCalled = 0;
            clientSyncDictionaryDirtyCalled = 0;
            serverSyncDictionary.OnDirty    = () => ++ serverSyncDictionaryDirtyCalled;
            clientSyncDictionary.OnDirty    = () => ++ clientSyncDictionaryDirtyCalled;
        }
Пример #10
0
        public bool AddConnectedClient(NetworkConnection conn, Player player)
        {
            bool result = !Players.ContainsKey(conn.connectionId);

            if (result)
            {
                Players.Add(conn.connectionId, player);
                ConnectedClients.Add(conn.connectionId);
            }
            return(result);
        }
Пример #11
0
 protected virtual void InitilizeItemSlots()
 {
     for (int i = 0; i < Capacity; i++)
     {
         var itemSlotData = new ItemSlotData
         {
             ParentNetId = AttachedNetworkIdentity.netId,
             SlotIndex   = i,
             SlotType    = ItemSlotType.Any
         };
         InventorySlotData.Add(i, itemSlotData);
     }
 }
Пример #12
0
        private void ProcessJoinClient()
        {
            var per  = State.Perception as BattlePerception;
            var view = per.View as GameViews.BattlePerceptionView;

            lock (syncRoot)
            {
                //send Init message.
                while (_addTemp.Count > 0)
                {
                    var client = _addTemp.Dequeue();
                    Clients.Add((long)client.UserState, client);
                    BattlePlayer battlePlayer;
                    //package
                    if (BattlePlayers.TryToGetValue((long)client.UserState, out battlePlayer))
                    {
                        var package = battlePlayer.GetNotifyPackage();
                        package.TimeNow = (Now.Time);
                        client.SendMessage(NetProtoTool.ToNetMessage(MessageClass.Notify, package));
                    }

                    var createNotify = view.GetInitNotify();
                    var messages     = ToMessages(createNotify);
                    //Notify package
                    foreach (var i in messages)
                    {
                        client.SendMessage(i);
                    }
                }
                while (_kickUsers.Count > 0)
                {
                    //kick
                    var u = _kickUsers.Dequeue();
                    BattlePlayers.Remove(u);
                    Clients.Remove(u);
                    per.State.Each <BattleCharacter>((el) =>
                    {
                        if (el.UserID == u)
                        {
                            GObject.Destory(el);
                        }
                        return(false);
                    });
                }
            }
        }
        public override CompetitorToOutrightLn MergeLineObject(CompetitorToOutrightLn objSource)
        {
            lock (m_oLocker)
            {
                CompetitorToOutrightLn cto = MergeLineObjectImp(objSource);

                PositionToOutrightDictionary di = m_diMatchIdToMPositionToOutrightDictionary.SafelyGetValue(cto.MatchId);

                if (di == null)
                {
                    di = new PositionToOutrightDictionary();
                    m_diMatchIdToMPositionToOutrightDictionary.Add(cto.MatchId, di);
                }

                di[cto.hometeam] = cto;

                return(cto);
            }
        }
Пример #14
0
        public void FromXml(XmlTextReader tr)
        {
            Debug.Assert(tr != null);

            string sCurrentTagName = string.Empty;

            while (tr.Read())
            {
                switch (tr.NodeType)
                {
                case XmlNodeType.Element:

                    sCurrentTagName = tr.Name;

                    if (sCurrentTagName == this.XmlTagName)
                    {
                        break;
                    }

                    break;

                case XmlNodeType.Text:

                    SerializableProperty sp = StringToSerializableProperty(sCurrentTagName, tr.Value);

                    if (sp != null)
                    {
                        m_di.Add(sCurrentTagName, sp);
                    }

                    break;

                case XmlNodeType.EndElement:

                    if (tr.Name == this.XmlTagName)
                    {
                        return;
                    }

                    break;
                }
            }
        }
Пример #15
0
        public ServerWorldSimluater BeginSimulater(BattlePlayer player)
        {
            if (isStoped)
            {
                return(null);
            }

            var worldSimulater = new ServerWorldSimluater(player.MapID,
                                                          Index++,
                                                          new List <BattlePlayer> {
                player
            });
            var client = Appliaction.Current.GetClientByID(player.ClientID);

            worldSimulater.AddClient(client);
            simluater.Add(worldSimulater.Index, worldSimulater);
            player.SimulaterIndex = worldSimulater.Index;
            return(worldSimulater);
        }
Пример #16
0
        public ServerWorldSimluater(int levelId, int index, List <BattlePlayer> battlePlayers)
        {
            LevelID     = levelId;
            Index       = index;
            IsCompleted = false;
            LevelData   = ExcelToJSONConfigManager.Current.GetConfigByID <BattleLevelData>(levelId);
            MapConfig   = ExcelToJSONConfigManager.Current.GetConfigByID <MapData>(LevelData.MapID);
            var mapGridName = MapConfig.LevelName + ".bin";
            var data        = ResourcesLoader.Singleton.GetMapGridByLevel(mapGridName);

            Grid         = new Astar.GridBase();
            Grid.maxX    = data.MaxX;
            Grid.maxY    = data.MaxY;
            Grid.maxZ    = data.MaxZ;
            Grid.offsetX = data.Offset.x;
            Grid.offsetY = data.Offset.y;
            Grid.offsetZ = data.Offset.z;
            Grid.sizeX   = data.Size.x;
            Grid.sizeY   = data.Size.y;
            Grid.sizeZ   = data.Size.z;
            Grid.grid    = new Node[Grid.maxX, Grid.maxY, Grid.maxZ];
            Data         = data;
            foreach (var i in data.Nodes)
            {
                Grid.grid[i.X, i.Y, i.Z] = new Astar.Node()
                {
                    x          = i.X,
                    isWalkable = i.IsWalkable,
                    y          = i.Y,
                    z          = i.Z
                };
            }

            BattlePlayers = new SyncDictionary <long, BattlePlayer>();
            foreach (var i in battlePlayers)
            {
                BattlePlayers.Add(i.User.UserID, i);
            }
            //this.Runner = new Thread(RunProcess);
        }
Пример #17
0
        public bool TryToGetUserData(long userID, out UserData data, bool reload = false)
        {
            if (reload)
            {
                userDatas.Remove(userID);
            }

            if (!userDatas.TryToGetValue(userID, out data))
            {
                using (var db = Appliaction.Current.GetDBContext())
                {
                    var user = db.TBGAmePlayer.Where(t => t.UserID == userID).SingleOrDefault();
                    if (user == null)
                    {
                        return(false);
                    }
                    var equip = db.TBPLayerEquip.Where(t => t.UserID == userID).SingleOrDefault();
                    var hero  = db.TBPLayerHero.Where(t => t.UserID == userID).SingleOrDefault();
                    if (hero == null)
                    {
                        return(false);
                    }

                    var package = DataManager.GetPackageFromTbPlayer(user, equip);
                    var dhero   = DataManager.GetDHeroFromTBhero(hero);
                    data = new UserData(dhero, package, user.Gold, user.Coin);

                    return(userDatas.Add(userID, data));
                }
            }
            else
            {
                data.Accessed();
                return(true);
            }
        }
Пример #18
0
        public bool Process(Queue.QueueItem item)
        {
            string    ftpHost = Settings.Default.FtpHost;
            Semaphore lockOne;

            lock (_syncRoot)
            {
                if (!_connLocks.ContainsKey(ftpHost))
                {
                    int semaphorePoolSize = Settings.Default.ConcurentFTPConnectionsCount;
                    lockOne = new Semaphore(0, semaphorePoolSize);
                    lockOne.Release(semaphorePoolSize);
                    _connLocks.Add(ftpHost, lockOne);
                }
                else
                {
                    lockOne = _connLocks[ftpHost];
                }
            }
            lockOne.WaitOne();
            try
            {
                bool          result = false;
                FTPConnection conn   = new FTPConnection();
                conn.Open(Settings.Default.FtpHost, Settings.Default.FtpUserName, Settings.Default.FtpPassword, FTPMode.Passive);
                conn.SetCurrentDirectory(Settings.Default.FtpTargetFolder);
                conn.SendFile(item.FileFullPath, FTPFileTransferType.Binary);
                conn.Close();
                result = true;
                return(result);
            }
            finally
            {
                lockOne.Release();
            }
        }
Пример #19
0
        public void AddUser(PlayerServerInfo user, int mapID)
        {
            var userInfo = new BattlePlayer
            {
                ClientID       = -1,
                User           = user,
                MapID          = mapID,
                StartTime      = DateTime.UtcNow,
                SimulaterIndex = -1
            };

            if (_battlePlayers.Add(user.UserID, userInfo))
            {
                if (!UserSimulaterMapping.Add(user.UserID, userInfo))
                {
                    DeleteUser(user.UserID, false);
                    Debuger.LogError("user " + user.UserID + " is in battle!");
                }
            }
            else
            {
                Debuger.LogError("user " + user.UserID + " is in battle!");
            }
        }
Пример #20
0
 public void WritingToReadOnlyThrows()
 {
     Assert.Throws <InvalidOperationException>(() => clientSyncDictionary.Add(50, "fail"));
 }
Пример #21
0
 public void SetSession(long userID, string session)
 {
     _sessions.Remove(userID);
     _sessions.Add(userID, session);
 }
Пример #22
0
        public void LoadAllConfig(string configRoot)
        {
            this.ConfigRoot = configRoot.StartsWith("" + Path.DirectorySeparatorChar, StringComparison.Ordinal)
                ? configRoot : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configRoot);

            _magicData = new SyncDictionary <string, MagicData>();
            _timeLines = new SyncDictionary <string, TimeLine>();
            _aiTree    = new SyncDictionary <string, TreeNode>();
            _levels    = new SyncDictionary <string, MapGridData>();
            var magics = Directory.GetFiles(Path.Combine(ConfigRoot, "Magics"), "*.xml");

            foreach (var i in magics)
            {
                var xml = File.ReadAllText(i, XmlParser.UTF8);
                var m   = XmlParser.DeSerialize <Layout.MagicData>(xml);
                _magicData.Add(m.key, m);
            }

            var timeLines = Directory.GetFiles(Path.Combine(ConfigRoot, "Layouts"), "*.xml");

            foreach (var i in timeLines)
            {
                var xml  = File.ReadAllText(i, XmlParser.UTF8);
                var line = XmlParser.DeSerialize <TimeLine>(xml);
                _timeLines.Add("Layouts/" + Path.GetFileName(i), line);
            }

            var aitrees = Directory.GetFiles(Path.Combine(ConfigRoot, "AI"), "*.xml");

            foreach (var i in aitrees)
            {
                var xml  = File.ReadAllText(i, XmlParser.UTF8);
                var note = XmlParser.DeSerialize <TreeNode>(xml);
                _aiTree.Add("AI/" + Path.GetFileName(i), note);
            }


            var mapFiles = Directory.GetFiles(Path.Combine(ConfigRoot, "LevelGrids"), "*.bin");

            foreach (var i in mapFiles)
            {
                var bytes   = File.ReadAllBytes(i);
                var mapdata = new Proto.MapGridData();
                using (var mem = new MemoryStream(bytes))
                {
                    using (var br = new BinaryReader(mem))
                    {
                        mapdata.ParseFormBinary(br);
                    }
                }

                _levels.Add(Path.GetFileName(i), mapdata);
            }

            var Manager = new ExcelToJSONConfigManager(this);

            var assemblyTypes = Manager.GetType().Assembly.GetTypes();
            var mothed        = Manager.GetType().GetMethod("GetConfigByID");

            foreach (var i in assemblyTypes)
            {
                if (i.IsSubclassOf(typeof(JSONConfigBase)))
                {
                    var m = mothed.MakeGenericMethod(i);
                    m.Invoke(Manager, new object[] { 0 });
                }
            }
        }
Пример #23
0
        //开始进入战斗
        internal ErrorCode BeginBattle(
            long userID,
            int mapID, int serverID, out GameServerInfo serverInfo)
        {
            serverInfo = null;
            var battleServer = ServerManager.Singleton.GetFreeBattleServerID();

            if (battleServer == null)
            {
                return(ErrorCode.NOFreeBattleServer);
            }
            UserServerInfo user;

            if (_servers.TryToGetValue(userID, out user))
            {
                var task = new Task_L2B_ExitUser {
                    UserID = user.UserID
                };
                var b       = ServerManager.Singleton.GetBattleServerMappingByServerID(user.BattleServerID);
                var bClient = Appliaction.Current.GetServerConnectByClientID(b.ClientID);
                if (bClient != null)
                {
                    NetProtoTool.SendTask(bClient, task);
                    //bClient.SendMessage(m);
                }
                return(ErrorCode.PlayerIsInBattle);
            }

            var su = _servers.Add(
                userID,
                new UserServerInfo
            {
                MapID          = mapID,
                BattleServerID = battleServer.ServerInfo.ServerID,
                GServerID      = serverID,
                UserID         = userID
            });

            if (su)
            {
                serverInfo = battleServer.ServerInfo;
                var gateserver = ServerManager.Singleton.GetGateServerMappingByServerID(serverID);
                var task       = new Task_L2B_StartBattle
                {
                    MapID = mapID,
                    Users = new List <PlayerServerInfo> {
                        new PlayerServerInfo {
                            UserID      = userID,
                            ServerID    = serverID,
                            ServiceHost = gateserver.ServiceHost,
                            ServicePort = gateserver.ServicePort
                        }
                    }
                };
                //task
                //var message = NetProtoTool.ToNetMessage(XNet.Libs.Net.MessageClass.Task, task);
                var serverConnect = Appliaction.Current.GetServerConnectByClientID(battleServer.ClientID);
                if (serverConnect == null)
                {
                    _servers.Remove(userID);
                    return(ErrorCode.BattleServerHasDisconnect);
                }
                NetProtoTool.SendTask(serverConnect, task);
                //serverConnect.SendMessage(message);
                return(Proto.ErrorCode.OK);
            }
            else
            {
                return(Proto.ErrorCode.PlayerIsInBattle);
            }
        }