예제 #1
0
 private void HandleStartPlayGame(GameClient client)
 {
     try
     {
         lock (this.Mutex)
         {
             if (client.ClientData.BeTrackingRoleID != 0 || client.ClientData.TrackingRoleIDList.Count != 0)
             {
                 bool toGuanZhanMap = true;
                 int  posX          = 0;
                 int  posY          = 0;
                 if (!this.GetGuanZhanPos(client.ClientData.MapCode, ref posX, ref posY))
                 {
                     toGuanZhanMap = false;
                 }
                 if (0 != client.ClientData.BeTrackingRoleID)
                 {
                     if (!toGuanZhanMap)
                     {
                         this.CancleTracking(client, true);
                     }
                     else
                     {
                         ClientManager.DoSpriteMapGridMove(client, 0);
                         GameClient beTClient = GameManager.ClientMgr.FindClient(client.ClientData.BeTrackingRoleID);
                         if (null != beTClient)
                         {
                             int result = 0;
                             client.sendCmd(1403, string.Format("{0}:{1}", result, beTClient.ClientData.RoleID), false);
                         }
                     }
                 }
                 List <int> tempTrackingRoleIDList = new List <int>(client.ClientData.TrackingRoleIDList);
                 foreach (int rid in tempTrackingRoleIDList)
                 {
                     GameClient tClient = GameManager.ClientMgr.FindClient(rid);
                     if (null != tClient)
                     {
                         if (!toGuanZhanMap)
                         {
                             this.CancleTracking(tClient, true);
                         }
                         else if (tClient.ClientData.MapCode != client.ClientData.MapCode)
                         {
                             GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), tClient, -1, client.ClientData.MapCode, client.ClientData.PosX, client.ClientData.PosY, client.ClientData.RoleDirection, 123);
                         }
                         else
                         {
                             GameManager.ClientMgr.NotifyOthersGoBack(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, tClient, client.ClientData.PosX, client.ClientData.PosY, -1);
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         DataHelper.WriteFormatExceptionLog(ex, "", false, false);
     }
 }
예제 #2
0
 private void Tracking(GameClient tClient, GameClient beTClient)
 {
     try
     {
         lock (this.Mutex)
         {
             this.CancleTracking(tClient, true);
             if (tClient.ClientData.MapCode != beTClient.ClientData.MapCode)
             {
                 GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), tClient, -1, beTClient.ClientData.MapCode, beTClient.ClientData.PosX, beTClient.ClientData.PosY, beTClient.ClientData.RoleDirection, 123);
             }
             else
             {
                 GameManager.ClientMgr.NotifyOthersGoBack(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, tClient, beTClient.ClientData.PosX, beTClient.ClientData.PosY, -1);
             }
             tClient.ClientData.BeTrackingRoleID = beTClient.ClientData.RoleID;
             if (!beTClient.ClientData.TrackingRoleIDList.Exists((int x) => x == tClient.ClientData.RoleID))
             {
                 beTClient.ClientData.TrackingRoleIDList.Add(tClient.ClientData.RoleID);
             }
             int result = 0;
             tClient.sendCmd(1403, string.Format("{0}:{1}", result, beTClient.ClientData.RoleID), false);
         }
     }
     catch (Exception ex)
     {
         DataHelper.WriteFormatExceptionLog(ex, "", false, false);
     }
 }
예제 #3
0
        public ReturnData GetUserReturnData(string userID, int zoneID)
        {
            ReturnData result = null;

            using (MyDbConnection3 conn = new MyDbConnection3(false))
            {
                string cmdText = string.Format("select vip,level,checkState,logTime from t_user_return where userid='{0}' and zoneID='{1}' and activityDay='{2}' and activityID='{3}'", new object[]
                {
                    userID,
                    zoneID,
                    UserReturnManager._activityInfo.ActivityDay,
                    UserReturnManager._activityInfo.ActivityID
                });
                MySQLDataReader reader = conn.ExecuteReader(cmdText, new MySQLParameter[0]);
                if (reader.Read())
                {
                    int inputMoneyInPeriod = DBQuery.GetUserInputMoney(TCPManager.getInstance().DBMgr, userID, 0, UserReturnManager._activityInfo.ActivityDay, "2050-01-01 00:00:00");
                    if (inputMoneyInPeriod < 0)
                    {
                        inputMoneyInPeriod = 0;
                    }
                    int roleYuanBaoInPeriod = Global.TransMoneyToYuanBao(inputMoneyInPeriod);
                    result = new ReturnData
                    {
                        Vip           = Convert.ToInt32(reader["vip"].ToString()),
                        Level         = Convert.ToInt32(reader["level"].ToString()),
                        StateCheck    = Convert.ToInt32(reader["checkState"].ToString()),
                        LogTime       = DateTime.Parse(reader["logTime"].ToString()),
                        LeiJiChongZhi = roleYuanBaoInPeriod
                    };
                }
            }
            return(result);
        }
예제 #4
0
 public void SendCmdOnStartPlayGame()
 {
     lock (this.DelayStartPlayGameMsgQueue)
     {
         while (this.DelayStartPlayGameMsgQueue.Count > 0)
         {
             TCPOutPacket tcpOutPacket = this.DelayStartPlayGameMsgQueue.Dequeue();
             TCPManager.getInstance().MySocketListener.SendData(this.ClientSocket, tcpOutPacket, true);
         }
     }
 }
예제 #5
0
 public void sendCmd(int cmdId, byte[] cmdData, bool waitEnterScene = false)
 {
     if (waitEnterScene && this.ClientData.FirstPlayStart)
     {
         this.SendCmdAfterStartPlayGame(cmdId, cmdData);
     }
     else
     {
         TCPManager.getInstance().MySocketListener.SendData(this.ClientSocket, TCPOutPacket.MakeTCPOutPacket(TCPOutPacketPool.getInstance(), cmdData, cmdId), true);
     }
 }
예제 #6
0
 public void sendCmd <T>(int cmdId, T cmdData, bool waitEnterScene = false)
 {
     if (waitEnterScene && this.ClientData.FirstPlayStart)
     {
         this.SendCmdAfterStartPlayGame <T>(cmdId, cmdData);
     }
     else
     {
         TCPManager.getInstance().MySocketListener.SendData(this.ClientSocket, DataHelper.ObjectToTCPOutPacket <T>(cmdData, TCPOutPacketPool.getInstance(), cmdId), true);
     }
 }
예제 #7
0
        private unsafe void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken userToken = e.UserToken as AsyncUserToken;
            TMSKSocket     s         = userToken.CurrentSocket;

            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                Interlocked.Add(ref this.totalBytesRead, (long)e.BytesTransferred);
                bool recvReturn = true;
                if (null != this.SocketReceived)
                {
                    if (GameManager.FlagUseWin32Decrypt)
                    {
                        int length = e.BytesTransferred;
                        fixed(byte *p = e.Buffer)
                        {
                            Win32API.SortBytes(p, e.Offset, e.BytesTransferred, s.SortKey64);
                        }
                    }
                    else
                    {
                        DataHelper.SortBytes(e.Buffer, e.Offset, e.BytesTransferred, s.SortKey64);
                    }
                    try
                    {
                        recvReturn = this.SocketReceived(this, e);
                    }
                    catch (Exception ex)
                    {
                        LogManager.WriteException(ex.ToString());
                        recvReturn = false;
                    }
                }
                if (recvReturn)
                {
                    if (!this._ReceiveAsync(e))
                    {
                        this.ProcessReceive(e);
                    }
                }
                else
                {
                    ushort lastPacketCmd = TCPManager.getInstance().LastPacketCmdID(s);
                    string reason        = string.Format("CMD={0}", ((TCPGameServerCmds)lastPacketCmd).ToString());
                    this.CloseClientSocket(e, reason);
                }
            }
            else
            {
                string reason = string.Format("[{0}]{1}", (int)e.SocketError, e.SocketError.ToString());
                this.CloseClientSocket(e, reason);
            }
        }
예제 #8
0
		public int createWanMoTaData(WanMotaInfo data)
		{
			lock (this.playerWanMoTaDatas)
			{
				if (this.playerWanMoTaDatas.ContainsKey(data.nRoleID))
				{
					return 0;
				}
				this.playerWanMoTaDatas.Add(data.nRoleID, data);
			}
			this.ModifyWanMoTaPaihangData(data, true);
			return WanMoTaDBController.getInstance().insertWanMoTaData(TCPManager.getInstance().DBMgr, data);
		}
        public static TCPProcessCmdResults ProcessRergressQueryUserInputMoneyCmd(DBManager dbMgr, TCPOutPacketPool pool, int nID, byte[] data, int count, out TCPOutPacket tcpOutPacket)
        {
            tcpOutPacket = null;
            string cmdData = null;

            try
            {
                cmdData = new UTF8Encoding().GetString(data, 0, count);
            }
            catch (Exception)
            {
                LogManager.WriteLog(LogTypes.Error, string.Format("解析指令字符串错误, CMD={0}", (TCPGameServerCmds)nID), null, true);
                tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                return(TCPProcessCmdResults.RESULT_DATA);
            }
            try
            {
                string[] fields = cmdData.Split(new char[]
                {
                    ':'
                });
                if (fields.Length != 3)
                {
                    LogManager.WriteLog(LogTypes.Error, string.Format("指令参数个数错误, CMD={0}, Recv={1}, CmdData={2}", (TCPGameServerCmds)nID, fields.Length, cmdData), null, true);
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                int        roleID   = Convert.ToInt32(fields[0]);
                string     fromDate = fields[1].Replace('$', ':');
                string     toDate   = fields[2].Replace('$', ':');
                DBRoleInfo roleInfo = dbMgr.GetDBRoleInfo(ref roleID);
                string     strcmd;
                if (null == roleInfo)
                {
                    strcmd       = string.Format("{0}:{1}:0", -1001, roleID);
                    tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, strcmd, nID);
                    return(TCPProcessCmdResults.RESULT_DATA);
                }
                int inputMoneyInPeriod  = DBQuery.GetUserInputMoney(TCPManager.getInstance().DBMgr, roleInfo.UserID, 0, fromDate, toDate);
                int roleYuanBaoInPeriod = Global.TransMoneyToYuanBao(inputMoneyInPeriod);
                strcmd       = string.Format("{0}:{1}", roleID, roleYuanBaoInPeriod);
                tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, strcmd, nID);
                return(TCPProcessCmdResults.RESULT_DATA);
            }
            catch (Exception ex)
            {
                DataHelper.WriteFormatExceptionLog(ex, "", false, false);
            }
            tcpOutPacket = TCPOutPacket.MakeTCPOutPacket(pool, "0", 30767);
            return(TCPProcessCmdResults.RESULT_DATA);
        }
예제 #10
0
        public void run()
        {
            int  cmdID           = 0;
            long processTime     = 0L;
            long processWaitTime = 0L;

            if (Monitor.TryEnter(this.session.Lock))
            {
                try
                {
                    long processBeginTime = TimeUtil.NowEx();
                    processWaitTime = processBeginTime - this.beginTime;
                    TCPCmdWrapper wrapper = this.session.getNextTCPCmdWrapper();
                    if (null != wrapper)
                    {
                        try
                        {
                            TCPCmdHandler.ProcessCmd(wrapper.TcpMgr, wrapper.TMSKSocket, wrapper.TcpClientPool, wrapper.TcpRandKey, wrapper.Pool, wrapper.NID, wrapper.Data, wrapper.Count);
                        }
                        catch (Exception ex)
                        {
                            DataHelper.WriteFormatExceptionLog(ex, string.Format("指令处理错误:{0},{1}", Global.GetDebugHelperInfo(wrapper.TMSKSocket), (TCPGameServerCmds)wrapper.NID), false, false);
                        }
                        ProcessSessionTask.processCmdNum += 1L;
                        processTime = TimeUtil.NowEx() - processBeginTime;
                        ProcessSessionTask.processTotalTime += processWaitTime + processTime;
                        cmdID = wrapper.NID;
                        wrapper.release();
                        wrapper = null;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    Monitor.Exit(this.session.Lock);
                }
                if (cmdID > 0)
                {
                    TCPManager.RecordCmdDetail2(cmdID, processTime, processWaitTime);
                }
            }
            else
            {
                TCPManager.getInstance().taskExecutor.scheduleExecute(this, 5L);
            }
        }
예제 #11
0
        /// <summary>
        /// 创建万魔塔数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public int createWanMoTaData(WanMotaInfo data)
        {
            lock (playerWanMoTaDatas)
            {
                if (playerWanMoTaDatas.ContainsKey(data.nRoleID))
                {
                    return(0);
                }

                playerWanMoTaDatas.Add(data.nRoleID, data);
            }

            // 添加更新万魔塔排行榜数据
            ModifyWanMoTaPaihangData(data, true);

            return(WanMoTaDBController.getInstance().insertWanMoTaData(TCPManager.getInstance().DBMgr, data));
        }
예제 #12
0
        public static TCPProcessCmdResults OnTeleport(GameClient client, int teleportID, TCPOutPacketPool pool, out TCPOutPacket tcpOutPacket)
        {
            tcpOutPacket = null;
            TCPProcessCmdResults result;

            if (client.ClientData.FuBenID != LuoLanFaZhenCopySceneManager.LuoLanFaZhenFubenID || client.ClientData.FuBenSeqID <= 0)
            {
                result = TCPProcessCmdResults.RESULT_FAILED;
            }
            else
            {
                SingleLuoLanFaZhenFubenData fubenData = LuoLanFaZhenCopySceneManager.GetFubenData(client.ClientData.FuBenSeqID);
                if (null == fubenData)
                {
                    result = TCPProcessCmdResults.RESULT_FAILED;
                }
                else
                {
                    FazhenMapData            mapdata  = null;
                    SingleFazhenTelegateData teledata = null;
                    lock (fubenData.MapDatas)
                    {
                        if (!fubenData.MapDatas.TryGetValue(client.ClientData.CopyMapID, out mapdata) || null == mapdata)
                        {
                            return(TCPProcessCmdResults.RESULT_FAILED);
                        }
                    }
                    if (mapdata.MapCode != client.ClientData.MapCode || mapdata.CopyMapID != client.ClientData.CopyMapID)
                    {
                        result = TCPProcessCmdResults.RESULT_FAILED;
                    }
                    else
                    {
                        lock (mapdata.Telegates)
                        {
                            if (!mapdata.Telegates.TryGetValue(teleportID, out teledata) || null == teledata)
                            {
                                return(TCPProcessCmdResults.RESULT_FAILED);
                            }
                        }
                        if (teledata.destMapCode <= 0)
                        {
                            result = TCPProcessCmdResults.RESULT_FAILED;
                        }
                        else
                        {
                            bool TeleToSpecial = false;
                            if (teledata.SpecialDestMapCode > 0)
                            {
                                if (0 != fubenData.SpecailBossLeftNum)
                                {
                                    int rand = Global.GetRandomNumber(0, 100);
                                    if (rand < LuoLanFaZhenCopySceneManager.SpecialTeleRate)
                                    {
                                        TeleToSpecial = true;
                                    }
                                }
                            }
                            if (TeleToSpecial)
                            {
                                GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), client, teleportID, teledata.SpecialDestMapCode, teledata.SpecialDestX, teledata.SpecialDestY, client.ClientData.RoleDirection, 123);
                            }
                            else
                            {
                                bool NeedSend = false;
                                lock (teledata)
                                {
                                    if (!teledata.usedAlready)
                                    {
                                        teledata.usedAlready = true;
                                        NeedSend             = true;
                                    }
                                }
                                if (NeedSend)
                                {
                                    FazhenMapProtoData senddata = new FazhenMapProtoData();
                                    senddata.listTelegate = new List <FazhenTelegateProtoData>();
                                    senddata.SrcMapCode   = mapdata.MapCode;
                                    FazhenTelegateProtoData gatedata_s = new FazhenTelegateProtoData();
                                    gatedata_s.gateId      = teledata.gateId;
                                    gatedata_s.DestMapCode = teledata.destMapCode;
                                    senddata.listTelegate.Add(gatedata_s);
                                    LuoLanFaZhenCopySceneManager.BroadMapData <FazhenMapProtoData>(685, senddata, mapdata.MapCode, client.ClientData.FuBenSeqID);
                                }
                                GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), client, teleportID, teledata.destMapCode, teledata.destX, teledata.destY, client.ClientData.RoleDirection, 123);
                            }
                            result = TCPProcessCmdResults.RESULT_OK;
                        }
                    }
                }
            }
            return(result);
        }
예제 #13
0
        public void UserReturnCheck(GameServerClient client, int nID, byte[] cmdParams, int count)
        {
            int isOldUser = 0;

            string[] fields = null;
            try
            {
                if (CheckHelper.CheckTCPCmdFields(nID, cmdParams, count, out fields, 3))
                {
                    if (UserReturnManager._activityInfo.IsOpen)
                    {
                        string userid  = fields[0];
                        string zoneid  = fields[1];
                        string logtime = fields[2];
                        int    level   = 0;
                        using (MyDbConnection3 conn = new MyDbConnection3(false))
                        {
                            string cmdText = string.Format("select * from t_user_return where userid='{0}' and activityDay='{1}' and activityID='{2}' and zoneID='{3}'", new object[]
                            {
                                userid,
                                UserReturnManager._activityInfo.ActivityDay,
                                UserReturnManager._activityInfo.ActivityID,
                                zoneid
                            });
                            if (null == conn.GetSingle(cmdText, 0, new MySQLParameter[0]))
                            {
                                int inputMoneyInPeriod  = DBQuery.GetUserInputMoney(TCPManager.getInstance().DBMgr, userid, 0, "2000-01-01 00:00:00", "2050-01-01 00:00:00");
                                int roleYuanBaoInPeriod = Global.TransMoneyToYuanBao(inputMoneyInPeriod);
                                if (UserReturnManager._activityInfo.VIPNeedExp <= roleYuanBaoInPeriod)
                                {
                                    cmdText = string.Format("select regtime from t_roles where userid='{0}' and regtime<'{1}'", userid, UserReturnManager._activityInfo.NotLoggedInBegin);
                                    if (null != conn.GetSingle(cmdText, 0, new MySQLParameter[0]))
                                    {
                                        cmdText = string.Format("select dayid from t_login where userid='{0}' and dayid>={1} and dayid<={2}", userid, Global.GetOffsetDay(UserReturnManager._activityInfo.NotLoggedInBegin), Global.GetOffsetDay(UserReturnManager._activityInfo.NotLoggedInFinish));
                                        if (null == conn.GetSingle(cmdText, 0, new MySQLParameter[0]))
                                        {
                                            cmdText = string.Format("select changelifecount*100+level as l from t_roles where userid='{0}' and zoneid='{1}' and isdel=0 order by l desc limit 1", userid, zoneid);
                                            level   = conn.GetSingleInt(cmdText, 0, new MySQLParameter[0]);
                                            if (UserReturnManager._activityInfo.Level <= level)
                                            {
                                                isOldUser = 1;
                                            }
                                        }
                                    }
                                }
                                cmdText = string.Format("insert into t_user_return values (0,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}' )", new object[]
                                {
                                    UserReturnManager._activityInfo.ActivityID,
                                    UserReturnManager._activityInfo.ActivityDay,
                                    zoneid,
                                    userid,
                                    UserReturnManager._activityInfo.VIPNeedExp,
                                    level,
                                    logtime,
                                    isOldUser
                                });
                                conn.ExecuteNonQuery(cmdText, 0);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DataHelper.WriteFormatExceptionLog(ex, "", false, false);
            }
            client.sendCmd <int>(nID, 1);
        }
예제 #14
0
 public void sendCmd(TCPOutPacket cmdData, bool pushBack = true)
 {
     TCPManager.getInstance().MySocketListener.SendData(this.ClientSocket, cmdData, pushBack);
 }
예제 #15
0
        public void run()
        {
            //                 lock (session.Lock)
            //                 {
            //
            //                 }

            int  cmdID           = 0;
            long processTime     = 0L;
            long processWaitTime = 0L;

            //因为业务层处理时未做同步,暂时锁会话,保证每个玩家的指令处理时线性的
            if (Monitor.TryEnter(session.Lock))
            {
                try
                {
                    long processBeginTime = TimeUtil.NowEx();
                    processWaitTime = processBeginTime - beginTime;

                    TCPCmdWrapper wrapper = session.getNextTCPCmdWrapper();
                    if (null != wrapper)
                    {
                        try
                        {
                            TCPCmdHandler.ProcessCmd(wrapper.TcpMgr, wrapper.TMSKSocket, wrapper.TcpClientPool, wrapper.TcpRandKey, wrapper.Pool, wrapper.NID, wrapper.Data, wrapper.Count);
                        }
                        catch (Exception ex)
                        {
                            DataHelper.WriteFormatExceptionLog(ex, string.Format("指令处理错误:{0},{1}", Global.GetDebugHelperInfo(wrapper.TMSKSocket), (TCPGameServerCmds)wrapper.NID), false);
                        }

                        processCmdNum++;
                        processTime       = (TimeUtil.NowEx() - processBeginTime);
                        processTotalTime += (processWaitTime + processTime);

                        cmdID = wrapper.NID;

                        wrapper.release();
                        wrapper = null;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    Monitor.Exit(session.Lock);
                }

                if (cmdID > 0)
                {
                    TCPManager.RecordCmdDetail2(cmdID, processTime, processWaitTime);
                }
            }
            else
            {
                //如果当session有指令正在处理,把当前指令重新丢进队列,延迟5毫秒处理,防止同一session占用过多线程,保证资源合理利用
                TCPManager.getInstance().taskExecutor.scheduleExecute(this, 5);
            }
        }
예제 #16
0
        private bool CreateOccupationSummoner(GameClient client, int nID, byte[] bytes, string[] cmdParams)
        {
            int PurchaseOccupationGoods = 0;

            lock (this.RuntimeData.Mutex)
            {
                PurchaseOccupationGoods = this.RuntimeData.PurchaseOccupationGoods;
            }
            bool result2;

            if (!SummonerData.CreateMapSet.Contains(client.CurrentMapCode))
            {
                string strcmd = string.Format("{0}:{1}", -21, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                {
                    "",
                    "",
                    "",
                    "",
                    "",
                    ""
                }));
                client.sendCmd(nID, strcmd, false);
                result2 = true;
            }
            else
            {
                int GoodsNum = Global.GetTotalGoodsCountByID(client, PurchaseOccupationGoods);
                if (GoodsNum <= 0)
                {
                    string strcmd = string.Format("{0}:{1}", -6, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                    {
                        "",
                        "",
                        "",
                        "",
                        "",
                        ""
                    }));
                    client.sendCmd(nID, strcmd, false);
                    result2 = true;
                }
                else
                {
                    TMSKSocket clientSocket = GameManager.OnlineUserSession.FindSocketByUserID(client.strUserID);
                    if (null == clientSocket)
                    {
                        result2 = true;
                    }
                    else
                    {
                        string   userID           = cmdParams[0];
                        string   userName         = cmdParams[1];
                        int      sex              = Convert.ToInt32(cmdParams[2]);
                        int      occup            = Convert.ToInt32(cmdParams[3]);
                        string[] nameAndPingTaiID = cmdParams[4].Split(new char[]
                        {
                            '$'
                        });
                        int    zoneID   = Convert.ToInt32(cmdParams[5]);
                        string deviceID = clientSocket.deviceID;
                        if (sex != 1 || occup != 5 || !GameManager.SummonerMgr.IsVersionSystemOpenOfSummoner())
                        {
                            string strcmd = string.Format("{0}:{1}", -12, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                            {
                                "",
                                "",
                                "",
                                "",
                                "",
                                ""
                            }));
                            client.sendCmd(nID, strcmd, false);
                            result2 = true;
                        }
                        else
                        {
                            string name = nameAndPingTaiID[0];
                            int    ret  = NameServerNamager.CheckInvalidCharacters(name, false);
                            if (ret <= 0)
                            {
                                string strcmd = string.Format("{0}:{1}", ret, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                                {
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    ""
                                }));
                                client.sendCmd(nID, strcmd, false);
                                result2 = true;
                            }
                            else if (!SingletonTemplate <NameManager> .Instance().IsNameLengthOK(name))
                            {
                                string strcmd = string.Format("{0}:{1}", -2, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                                {
                                    "",
                                    "",
                                    "",
                                    "",
                                    "",
                                    ""
                                }));
                                client.sendCmd(nID, strcmd, false);
                                result2 = true;
                            }
                            else
                            {
                                ret = NameServerNamager.RegisterNameToNameServer(zoneID, userID, nameAndPingTaiID, 0, 0);
                                if (ret <= 0)
                                {
                                    string strcmd = string.Format("{0}:{1}", ret, string.Format("{0}${1}${2}${3}${4}${5}", new object[]
                                    {
                                        "",
                                        "",
                                        "",
                                        "",
                                        "",
                                        ""
                                    }));
                                    client.sendCmd(nID, strcmd, false);
                                    result2 = true;
                                }
                                else
                                {
                                    int NotifyLeftTime = 0;
                                    if (!SingletonTemplate <CreateRoleLimitManager> .Instance().IfCanCreateRole(userID, userName, deviceID, ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString(), out NotifyLeftTime))
                                    {
                                        string strcmd = string.Format("{0}:{1}", -7, NotifyLeftTime);
                                        client.sendCmd(nID, strcmd, false);
                                        result2 = true;
                                    }
                                    else
                                    {
                                        string               cmddata      = string.Format("{0}:{1}", new UTF8Encoding().GetString(bytes, 0, bytes.Length), 1);
                                        byte[]               bytesCmd     = new UTF8Encoding().GetBytes(cmddata);
                                        TCPOutPacket         tcpOutPacket = null;
                                        TCPProcessCmdResults result       = Global.TransferRequestToDBServer(TCPManager.getInstance(), clientSocket, Global._TCPManager.tcpClientPool, TCPManager.getInstance().tcpRandKey, Global._TCPManager.TcpOutPacketPool, 102, bytesCmd, bytesCmd.Length, out tcpOutPacket, clientSocket.ServerId);
                                        if (null == tcpOutPacket)
                                        {
                                            result2 = true;
                                        }
                                        else
                                        {
                                            tcpOutPacket.PacketCmdID = (ushort)nID;
                                            string strCmdResult = null;
                                            tcpOutPacket.GetPacketCmdData(out strCmdResult);
                                            client.sendCmd(tcpOutPacket, true);
                                            if (null != strCmdResult)
                                            {
                                                string[] ResultField = strCmdResult.Split(new char[]
                                                {
                                                    ':'
                                                });
                                                if (ResultField.Length == 2 && Global.SafeConvertToInt32(ResultField[0]) == 1)
                                                {
                                                    bool usedBinding     = false;
                                                    bool usedTimeLimited = false;
                                                    GameManager.ClientMgr.NotifyUseGoods(Global._TCPManager.MySocketListener, Global._TCPManager.tcpClientPool, Global._TCPManager.TcpOutPacketPool, client, PurchaseOccupationGoods, 1, false, out usedBinding, out usedTimeLimited, false);
                                                    SingletonTemplate <CreateRoleLimitManager> .Instance().ModifyCreateRoleNum(userID, userName, deviceID, ((IPEndPoint)clientSocket.RemoteEndPoint).Address.ToString());

                                                    string[] fields = ResultField[1].Split(new char[]
                                                    {
                                                        '$'
                                                    });
                                                    int newRoleID = Global.SafeConvertToInt32(fields[0]);
                                                    client.sendCmd <int>(13999, newRoleID, false);
                                                }
                                            }
                                            result2 = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(result2);
        }
예제 #17
0
        /// <summary>
        /// Initialize the game resource information
        /// The original Window_Loaded(object sender, RoutedEventArgs e)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void InitServer()
        {
            InitProgramExtName();

            System.Console.WriteLine("The language file is being initialized");

            Global.LoadLangDict();

            XElement xml = null;

            System.Console.WriteLine("The system configuration file is being initialized");

            try
            {
                xml = XElement.Load(@"AppConfig.xml");
            }
            catch (Exception)
            {
                throw new Exception(string.Format("Load xml file at startup: {0} failed", @"AppConfig.xml"));
            }

            // Program log level
            LogManager.LogTypeToWrite = (LogTypes)(int)Global.GetSafeAttributeLong(xml, "Server", "LogType");

            // Event log level
            GameDBManager.SystemServerSQLEvents.EventLevel = (EventLevels)(int)Global.GetSafeAttributeLong(xml, "Server", "EventLevel");

            int dbLog = Math.Max(0, (int)Global.GetSafeAttributeLong(xml, "DBLog", "DBLogEnable"));

            //Write the log in the cache to the file
            //GameDBManager.DBEventsWriter.Enable = (dbLog > 0);
            //GameDBManager.DBEventsWriter.EventDiskWriter.EventRootPath = Global.GetSafeAttributeStr(xml, "DBLog", "Path");
            //GameDBManager.DBEventsWriter.MaxCacheCount = 10000 * 10;

            GameDBManager.ZoneID = (int)Global.GetSafeAttributeLong(xml, "Zone", "ID");

            string uname   = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "uname"), "eabcix675u49,/", "3&3i4x4^+-0");
            string upasswd = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "upasswd"), "eabcix675u49,/", "3&3i4x4^+-0");

            System.Console.WriteLine("The number of data connection pools the server is building: {0}", (int)Global.GetSafeAttributeLong(xml, "Database", "maxConns"));
            System.Console.WriteLine("Database address: {0}", Global.GetSafeAttributeStr(xml, "Database", "ip"));
            System.Console.WriteLine("Name database: {0}", Global.GetSafeAttributeStr(xml, "Database", "dname"));
            System.Console.WriteLine("Database character set: {0}", Global.GetSafeAttributeStr(xml, "Database", "names"));

            DBConnections.dbNames = Global.GetSafeAttributeStr(xml, "Database", "names");

            System.Console.WriteLine("The database connection is being initialized");

            //long ticks = DateTime.Now.Ticks;
            _DBManger.LoadDatabase(new MySQLConnectionString(
                                       Global.GetSafeAttributeStr(xml, "Database", "ip"),
                                       Global.GetSafeAttributeStr(xml, "Database", "dname"),
                                       uname,
                                       upasswd),
                                   (int)Global.GetSafeAttributeLong(xml, "Database", "maxConns"),
                                   (int)Global.GetSafeAttributeLong(xml, "Database", "codePage"));

            //Verify area code
            ValidateZoneID();

            //Prepare the necessary data sheet
            GameDBManager.DBName = Global.GetSafeAttributeStr(xml, "Database", "dname");
            DBWriter.ValidateDatabase(_DBManger, GameDBManager.DBName);

            //Initialize the database since the growth value
            if (!Global.InitDBAutoIncrementValues(_DBManger))
            {
                System.Console.WriteLine("There is a fatal error. Please enter exit and y to exit");
                return;
            }

            //DBWriter.ClearUnusedGoodsData(_DBManger, true);
            //MessageBox.Show(string.Format("Add a total cost: {0}", (DateTime.Now.Ticks - ticks) / 10000));

            //Line management
            LineManager.LoadConfig(xml);

            System.Console.WriteLine("The network is being initialized");

//             _TCPManager = new TCPManager((int)Global.GetSafeAttributeLong(xml, "Socket", "capacity"));

            _TCPManager = TCPManager.getInstance();
            _TCPManager.initialize((int)Global.GetSafeAttributeLong(xml, "Socket", "capacity"));

            //Start the communication management object
            _TCPManager.DBMgr      = _DBManger;
            _TCPManager.RootWindow = this;
            _TCPManager.Start(Global.GetSafeAttributeStr(xml, "Socket", "ip"),
                              (int)Global.GetSafeAttributeLong(xml, "Socket", "port"));

            System.Console.WriteLine("Configuring background threads");

            //Set the background worker thread
            eventWorker         = new BackgroundWorker();
            eventWorker.DoWork += eventWorker_DoWork;

            updateMoneyWorker         = new BackgroundWorker();
            updateMoneyWorker.DoWork += updateMoneyWorker_DoWork;

            releaseMemoryWorker         = new BackgroundWorker();
            releaseMemoryWorker.DoWork += releaseMemoryWorker_DoWork;

            updateLiPinMaWorker         = new BackgroundWorker();
            updateLiPinMaWorker.DoWork += updateLiPinMaWorker_DoWork;

            updatePreNamesWorker         = new BackgroundWorker();
            updatePreNamesWorker.DoWork += updatePreNamesWorker_DoWork;

            updatePaiHangWorker         = new BackgroundWorker();
            updatePaiHangWorker.DoWork += updatePaiHangWorker_DoWork;

            dbWriterWorker         = new BackgroundWorker();
            dbWriterWorker.DoWork += dbWriterWorker_DoWork;

            updateLastMailWorker         = new BackgroundWorker();
            updateLastMailWorker.DoWork += updateLastMail_DoWork;

            MainDispatcherWorker         = new BackgroundWorker();
            MainDispatcherWorker.DoWork += MainDispatcherWorker_DoWork;

            //Whether to display the exception when the dialog box
            UnhandedException.ShowErrMsgBox = false;

            //Start the Global Service Manager
            GlobalServiceManager.initialize();
            GlobalServiceManager.startup();

            //Start the main loop scheduling thread
            if (!MainDispatcherWorker.IsBusy)
            {
                MainDispatcherWorker.RunWorkerAsync();
            }

            //ProgramExtName = string.Format("{0}@{1}", Global.GetSafeAttributeStr(xml, "Database", "dname"), GameDBManager.ZoneID);
            DBWriter.UpdateGameConfig(_DBManger, "gamedb_version", GetVersionDateTime());

            System.Console.WriteLine("The system is finished");
        }
예제 #18
0
        /*
         * /// <summary>
         * /// 缓存锁
         * /// </summary>
         * private object _CachingBytesDataMutex = new object();
         *
         * /// <summary>
         * /// 上次缓存的时间
         * /// </summary>
         * private long _LastCachingBytesDataTicks = 0;
         *
         * /// <summary>
         * /// 缓存的数据
         * /// </summary>
         * private byte[] _CachingBytesData = null;
         *
         * /// <summary>
         * /// 从缓存中获取怪物对象
         * /// </summary>
         * /// <returns></returns>
         * private byte[] GetBytesDataFromCaching()
         * {
         *  long ticks = DateTime.Now.Ticks / 10000;
         *  lock (_CachingBytesDataMutex)
         *  {
         *      if (null != _CachingBytesData)
         *      {
         *          if (ticks - _LastCachingBytesDataTicks < GameManager.MaxCachingClientToClientBytesDataTicks)
         *          {
         *              //System.Diagnostics.Debug.WriteLine(string.Format("从角色缓存中读取数据"));
         *              return _CachingBytesData;
         *          }
         *      }
         *
         *      _LastCachingBytesDataTicks = ticks;
         *      RoleData roleData = Global.ClientDataToRoleData2(this.ClientData);
         *      _CachingBytesData = DataHelper.ObjectToBytes<RoleData>(roleData);
         *      return _CachingBytesData;
         *  }
         * }
         *
         * /// <summary>
         * /// 释放缓存
         * /// </summary>
         * public void ReleaseBytesDataFromCaching(bool bForce = false)
         * {
         *  lock (_CachingBytesDataMutex)
         *  {
         *      if (null != _CachingBytesData)
         *      {
         *          long ticks = DateTime.Now.Ticks / 10000;
         *          if (bForce || ticks - _LastCachingBytesDataTicks >= GameManager.MaxCachingClientToClientBytesDataTicks)
         *          {
         *              //System.Diagnostics.Debug.WriteLine(string.Format("将角色缓存释放"));
         *              _CachingBytesData = null;
         *          }
         *      }
         *  }
         * }
         *
         * /// <summary>
         * /// 从缓存中获取角色对象
         * /// </summary>
         * /// <returns></returns>
         * public TCPOutPacket GetTCPOutPacketFromCaching(int cmdID)
         * {
         *  byte[] bytesCmd = this.GetBytesDataFromCaching();
         *  return TCPOutPacket.MakeTCPOutPacket(Global._TCPManager.TcpOutPacketPool, bytesCmd, 0, bytesCmd.Length, cmdID);
         * }
         */
        #endregion

        #region 指令发送

        /// <summary>
        /// 向“自己”发送指令
        /// </summary>
        public void sendCmd(int cmdId, string cmdData)
        {
            TCPManager.getInstance().MySocketListener.SendData(ClientSocket, TCPOutPacket.MakeTCPOutPacket(TCPOutPacketPool.getInstance(), cmdData, cmdId));
        }
예제 #19
0
        public void InitServer()
        {
            Program.InitProgramExtName();
            Console.WriteLine("正在初始化语言文件");
            Global.LoadLangDict();
            if (!IpLibrary.loadIpLibrary("qqwry.dat"))
            {
                throw new Exception(string.Format("启动时加载IP库: {0} 失败", "qqwry.dat"));
            }
            XElement xml = null;

            Console.WriteLine("正在初始化系统配置文件");
            try
            {
                xml = XElement.Load("AppConfig.xml");
            }
            catch (Exception)
            {
                throw new Exception(string.Format("启动时加载xml文件: {0} 失败", "AppConfig.xml"));
            }
            LogManager.LogTypeToWrite = (LogTypes)Global.GetSafeAttributeLong(xml, "Server", "LogType");
            GameDBManager.SystemServerSQLEvents.EventLevel = (EventLevels)Global.GetSafeAttributeLong(xml, "Server", "EventLevel");
            int dbLog = Math.Max(0, (int)Global.GetSafeAttributeLong(xml, "DBLog", "DBLogEnable"));

            GameDBManager.ZoneID = (int)Global.GetSafeAttributeLong(xml, "Zone", "ID");
            string startURL  = null;
            string chargeKey = "";
            string serverKey = "";

            try
            {
                startURL  = Global.GetSafeAttributeStr(xml, "Zone", "URL");
                chargeKey = Global.GetSafeAttributeStr(xml, "Platform", "GameKey");
                serverKey = Global.GetSafeAttributeStr(xml, "Platform", "ServerKey");
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(LogTypes.Fatal, "读取AppConfig.xml配置文件出错" + ex.Message, ex, true);
            }
            if (!string.IsNullOrEmpty(startURL))
            {
                GetCDBInfoReq cdbServerReq = new GetCDBInfoReq();
                cdbServerReq.PTID     = Global.GetSafeAttributeStr(xml, "Zone", "PTID");
                cdbServerReq.ServerID = GameDBManager.ZoneID.ToString();
                cdbServerReq.Gamecode = Global.GetSafeAttributeStr(xml, "Zone", "GameCode");
                byte[] responseData = null;
                byte[] clientBytes  = DataHelper.ObjectToBytes <GetCDBInfoReq>(cdbServerReq);
                for (int i = 1; i <= 5; i++)
                {
                    responseData = WebHelper.RequestByPost(startURL, clientBytes, 5000, 30000);
                    if (responseData != null)
                    {
                        break;
                    }
                    Console.WriteLine("第{0}次获取启动信息失败,2秒后重试", i);
                    Thread.Sleep(2000);
                }
                if (responseData == null)
                {
                    throw new Exception(string.Format("请求启动信息失败", new object[0]));
                }
                ServerDBInfo databaseInfo = DataHelper.BytesToObject <ServerDBInfo>(responseData, 0, responseData.Length);
                if (databaseInfo == null)
                {
                    throw new Exception(string.Format("请求启动信息 解析失败", new object[0]));
                }
                GameDBManager.serverDBInfo           = databaseInfo;
                GameDBManager.serverDBInfo.userName  = StringEncrypt.Decrypt(GameDBManager.serverDBInfo.userName, "eabcix675u49,/", "3&3i4x4^+-0");
                GameDBManager.serverDBInfo.uPassword = StringEncrypt.Decrypt(GameDBManager.serverDBInfo.uPassword, "eabcix675u49,/", "3&3i4x4^+-0");
                if (GameDBManager.serverDBInfo.InternalIP != Global.GetInternalIP())
                {
                    throw new Exception(string.Format("请求启动信息 内网IP不匹配", new object[0]));
                }
                string tmpName = string.Format("{0}_game_{1}", cdbServerReq.Gamecode, cdbServerReq.ServerID);
                if (tmpName != GameDBManager.serverDBInfo.dbName)
                {
                    throw new Exception(string.Format("请求启动信息 dbName不匹配", new object[0]));
                }
            }
            else
            {
                GameDBManager.serverDBInfo            = new ServerDBInfo();
                GameDBManager.serverDBInfo.userName   = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "uname"), "eabcix675u49,/", "3&3i4x4^+-0");
                GameDBManager.serverDBInfo.uPassword  = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "upasswd"), "eabcix675u49,/", "3&3i4x4^+-0");
                GameDBManager.serverDBInfo.strIP      = Global.GetSafeAttributeStr(xml, "Database", "ip");
                GameDBManager.serverDBInfo.Port       = (int)Global.GetSafeAttributeLong(xml, "Database", "port");
                GameDBManager.serverDBInfo.dbName     = Global.GetSafeAttributeStr(xml, "Database", "dname");
                GameDBManager.serverDBInfo.maxConns   = (int)Global.GetSafeAttributeLong(xml, "Database", "maxConns");
                GameDBManager.serverDBInfo.InternalIP = Global.GetInternalIP();
                GameDBManager.serverDBInfo.ChargeKey  = chargeKey;
                GameDBManager.serverDBInfo.ServerKey  = serverKey;
            }
            GameDBManager.serverDBInfo.ChargeKey = StringEncrypt.Decrypt(GameDBManager.serverDBInfo.ChargeKey, "eabcix675u49,/", "3&3i4x4^+-0");
            GameDBManager.serverDBInfo.ServerKey = StringEncrypt.Decrypt(GameDBManager.serverDBInfo.ServerKey, "eabcix675u49,/", "3&3i4x4^+-0");
            GameDBManager.serverDBInfo.DbNames   = Global.GetSafeAttributeStr(xml, "Database", "names");
            GameDBManager.serverDBInfo.CodePage  = (int)Global.GetSafeAttributeLong(xml, "Database", "codePage");
            Console.WriteLine("服务器正在建立数据链接池个数: {0}", GameDBManager.serverDBInfo.maxConns);
            Console.WriteLine("数据库地址: {0}", GameDBManager.serverDBInfo.strIP);
            Console.WriteLine("数据库名称: {0}", GameDBManager.serverDBInfo.dbName);
            Console.WriteLine("数据库字符集: {0}", GameDBManager.serverDBInfo.DbNames);
            Console.WriteLine("数据库代码页: {0}", GameDBManager.serverDBInfo.CodePage);
            DBConnections.dbNames = GameDBManager.serverDBInfo.DbNames;
            Console.WriteLine("正在初始化数据库链接");
            MySQLConnectionString connectStr = new MySQLConnectionString(GameDBManager.serverDBInfo.strIP, GameDBManager.serverDBInfo.dbName, GameDBManager.serverDBInfo.userName, GameDBManager.serverDBInfo.uPassword);

            this._DBManger.LoadDatabase(connectStr, GameDBManager.serverDBInfo.maxConns, GameDBManager.serverDBInfo.CodePage);
            Program.ValidateZoneID();
            GameDBManager.DBName = Global.GetSafeAttributeStr(xml, "Database", "dname");
            DBWriter.ValidateDatabase(this._DBManger, GameDBManager.DBName);
            if (!Global.InitDBAutoIncrementValues(this._DBManger))
            {
                Console.WriteLine("存在致命错误,请输入exit 和 y 退出");
            }
            else
            {
                LineManager.LoadConfig();
                Console.WriteLine("正在初始化网络");
                this._TCPManager = TCPManager.getInstance();
                this._TCPManager.initialize((int)Global.GetSafeAttributeLong(xml, "Socket", "capacity"));
                this._TCPManager.DBMgr      = this._DBManger;
                this._TCPManager.RootWindow = this;
                this._TCPManager.Start(Global.GetSafeAttributeStr(xml, "Socket", "ip"), (int)Global.GetSafeAttributeLong(xml, "Socket", "port"));
                PlatTCPManager.getInstance().initialize((int)Global.GetSafeAttributeLong(xml, "Platform", "capacity"));
                PlatTCPManager.getInstance().Start(Global.GetSafeAttributeStr(xml, "Platform", "ip"), (int)Global.GetSafeAttributeLong(xml, "Platform", "port"));
                Console.WriteLine("正在配置后台线程");
                this.eventWorker                   = new BackgroundWorker();
                this.eventWorker.DoWork           += this.eventWorker_DoWork;
                this.updateMoneyWorker             = new BackgroundWorker();
                this.updateMoneyWorker.DoWork     += this.updateMoneyWorker_DoWork;
                this.releaseMemoryWorker           = new BackgroundWorker();
                this.releaseMemoryWorker.DoWork   += this.releaseMemoryWorker_DoWork;
                this.updateLiPinMaWorker           = new BackgroundWorker();
                this.updateLiPinMaWorker.DoWork   += this.updateLiPinMaWorker_DoWork;
                this.updatePreDeleteWorker         = new BackgroundWorker();
                this.updatePreDeleteWorker.DoWork += this.updatePreDeleteRoleWorker_DoWork;
                this.updatePreNamesWorker          = new BackgroundWorker();
                this.updatePreNamesWorker.DoWork  += this.updatePreNamesWorker_DoWork;
                this.updatePaiHangWorker           = new BackgroundWorker();
                this.updatePaiHangWorker.DoWork   += this.updatePaiHangWorker_DoWork;
                this.dbWriterWorker                = new BackgroundWorker();
                this.dbWriterWorker.DoWork        += new DoWorkEventHandler(this.dbWriterWorker_DoWork);
                this.dbGoodsBakTableWorker         = new BackgroundWorker();
                this.dbGoodsBakTableWorker.DoWork += new DoWorkEventHandler(this.dbGoodsBakTableWorker_DoWork);
                this.updateLastMailWorker          = new BackgroundWorker();
                this.updateLastMailWorker.DoWork  += this.updateLastMail_DoWork;
                this.updateGroupMailWorker         = new BackgroundWorker();
                this.updateGroupMailWorker.DoWork += this.updateGroupMail_DoWork;
                this.updateFacebookWorker          = new BackgroundWorker();
                this.updateFacebookWorker.DoWork  += this.updateFacebook_DoWork;
                this.MainDispatcherWorker          = new BackgroundWorker();
                this.MainDispatcherWorker.DoWork  += new DoWorkEventHandler(this.MainDispatcherWorker_DoWork);
                this.userReturnCheckWorker         = new BackgroundWorker();
                this.userReturnCheckWorker.DoWork += this.UserReturnCheckWorker_DoWork;
                this.updateTenWorker               = new BackgroundWorker();
                this.updateTenWorker.DoWork       += this.updateTen_DoWork;
                this.updateGiftCodeWorker          = new BackgroundWorker();
                this.updateGiftCodeWorker.DoWork  += this.updateGiftCode_DoWork;
                UnhandedException.ShowErrMsgBox    = false;
                GlobalServiceManager.initialize();
                GlobalServiceManager.startup();
                if (!this.MainDispatcherWorker.IsBusy)
                {
                    this.MainDispatcherWorker.RunWorkerAsync();
                }
                GameDBManager.GameConfigMgr.UpdateGameConfigItem("gamedb_version", Program.GetVersionDateTime());
                DBWriter.UpdateGameConfig(this._DBManger, "gamedb_version", Program.GetVersionDateTime());
                Console.WriteLine("系统启动完毕");
            }
        }
예제 #20
0
 /// <summary>
 /// 向“自己”发送指令
 /// </summary>
 public void sendCmd <T>(int cmdId, T cmdData)
 {
     TCPManager.getInstance().MySocketListener.SendData(ClientSocket, DataHelper.ObjectToTCPOutPacket <T>(cmdData, TCPOutPacketPool.getInstance(), cmdId));
 }
예제 #21
0
 public void sendCmd(TCPOutPacket cmdData)
 {
     TCPManager.getInstance().MySocketListener.SendData(ClientSocket, cmdData);
 }
예제 #22
0
        //玩家使用传送门
        public static TCPProcessCmdResults OnTeleport(GameClient client, int teleportID, TCPOutPacketPool pool, out TCPOutPacket tcpOutPacket)
        {
            tcpOutPacket = null;

            if (client.ClientData.FuBenID != LuoLanFaZhenFubenID || client.ClientData.FuBenSeqID <= 0)
            {
                return(TCPProcessCmdResults.RESULT_FAILED);
            }

            SingleLuoLanFaZhenFubenData fubenData = GetFubenData(client.ClientData.FuBenSeqID);

            if (null == fubenData)
            {
                return(TCPProcessCmdResults.RESULT_FAILED);
            }

            FazhenMapData            mapdata  = null;
            SingleFazhenTelegateData teledata = null;

            lock (fubenData.MapDatas)
            {
                if (!fubenData.MapDatas.TryGetValue(client.ClientData.CopyMapID, out mapdata) || null == mapdata)
                {
                    return(TCPProcessCmdResults.RESULT_FAILED);
                }
            }

            if (mapdata.MapCode != client.ClientData.MapCode || mapdata.CopyMapID != client.ClientData.CopyMapID)
            {
                return(TCPProcessCmdResults.RESULT_FAILED);
            }

            lock (mapdata.Telegates)
            {
                //如果找不到这个传送门,说明这是个普通的传送点
                if (!mapdata.Telegates.TryGetValue(teleportID, out teledata) || null == teledata)
                {
                    return(TCPProcessCmdResults.RESULT_FAILED);
                }
            }

            if (teledata.destMapCode <= 0)
            {
                return(TCPProcessCmdResults.RESULT_FAILED);
            }

            //判断是否随机传到特殊地图
            bool TeleToSpecial = false;

            if (teledata.SpecialDestMapCode > 0)
            {
                //[bing] 有些人进入特殊地图时 该地图怪物已经被杀了 导致进入地图后又要返回 所以预先判断有无怪物 没怪物则不传送特殊地
                if (0 != fubenData.SpecailBossLeftNum)
                {
                    int rand = Global.GetRandomNumber(0, 100);
                    //是否随机传送到特殊地图
                    if (rand < SpecialTeleRate)
                    {
                        //传送到特殊地图
                        TeleToSpecial = true;
                    }
                }
            }

            if (TeleToSpecial)
            {
                //传送到特殊地图teledata.SpecialDestMapCode
                GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), client, teleportID,
                                                teledata.SpecialDestMapCode, teledata.SpecialDestX, teledata.SpecialDestY, client.ClientData.RoleDirection,
                                                (int)TCPGameServerCmds.CMD_SPR_MAPCHANGE);
            }
            else   //传送到普通地图
            {
                //是否已经用过?
                bool NeedSend = false;
                lock (teledata)
                {
                    if (!teledata.usedAlready)
                    {
                        //没用过
                        teledata.usedAlready = true;
                        NeedSend             = true;
                    }
                }

                if (NeedSend)
                {
                    //通知副本内所有玩家传送门被用过后的数据
                    FazhenMapProtoData senddata = new FazhenMapProtoData();
                    senddata.listTelegate = new List <FazhenTelegateProtoData>();
                    senddata.SrcMapCode   = mapdata.MapCode;

                    FazhenTelegateProtoData gatedata_s = new FazhenTelegateProtoData();
                    gatedata_s.gateId      = teledata.gateId;
                    gatedata_s.DestMapCode = teledata.destMapCode;
                    senddata.listTelegate.Add(gatedata_s);

                    //发送此传送门数据给地图内所有玩家
                    BroadMapData <FazhenMapProtoData>((int)TCPGameServerCmds.CMD_MAP_TELEPORT, senddata, mapdata.MapCode, client.ClientData.FuBenSeqID);
                }

                //传送到普通地图
                GameManager.ClientMgr.ChangeMap(TCPManager.getInstance().MySocketListener, TCPOutPacketPool.getInstance(), client, teleportID,
                                                teledata.destMapCode, teledata.destX, teledata.destY, client.ClientData.RoleDirection,
                                                (int)TCPGameServerCmds.CMD_SPR_MAPCHANGE);
            }

            return(TCPProcessCmdResults.RESULT_OK);
        }
예제 #23
0
        public void InitServer()
        {
            Program.InitProgramExtName();
            Console.WriteLine("正在初始化语言文件");
            Global.LoadLangDict();
            XElement xml = null;

            Console.WriteLine("正在初始化系统配置文件");
            try
            {
                xml = XElement.Load("AppConfig.xml");
            }
            catch (Exception)
            {
                throw new Exception(string.Format("启动时加载xml文件: {0} 失败", "AppConfig.xml"));
            }
            LogManager.LogTypeToWrite = (LogTypes)Global.GetSafeAttributeLong(xml, "Server", "LogType");
            GameDBManager.SystemServerSQLEvents.EventLevel = (EventLevels)Global.GetSafeAttributeLong(xml, "Server", "EventLevel");
            int dbLog = Math.Max(0, (int)Global.GetSafeAttributeLong(xml, "DBLog", "DBLogEnable"));

            GameDBManager.ZoneID = (int)Global.GetSafeAttributeLong(xml, "Zone", "ID");
            string uname   = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "uname"), "eabcix675u49,/", "3&3i4x4^+-0");
            string upasswd = StringEncrypt.Decrypt(Global.GetSafeAttributeStr(xml, "Database", "upasswd"), "eabcix675u49,/", "3&3i4x4^+-0");

            Console.WriteLine("服务器正在建立数据链接池个数: {0}", (int)Global.GetSafeAttributeLong(xml, "Database", "maxConns"));
            Console.WriteLine("数据库地址: {0}", Global.GetSafeAttributeStr(xml, "Database", "ip"));
            Console.WriteLine("数据库名称: {0}", Global.GetSafeAttributeStr(xml, "Database", "dname"));
            Console.WriteLine("数据库字符集: {0}", Global.GetSafeAttributeStr(xml, "Database", "names"));
            DBConnections.dbNames = Global.GetSafeAttributeStr(xml, "Database", "names");
            Console.WriteLine("正在初始化数据库链接");
            this._DBManger.LoadDatabase(new MySQLConnectionString(Global.GetSafeAttributeStr(xml, "Database", "ip"), Global.GetSafeAttributeStr(xml, "Database", "dname"), uname, upasswd), (int)Global.GetSafeAttributeLong(xml, "Database", "maxConns"), (int)Global.GetSafeAttributeLong(xml, "Database", "codePage"));
            string          strTableName = "t_log_" + DateTime.Now.ToString("yyyyMMdd");
            MySQLConnection conn         = this._DBManger.DBConns.PopDBConnection();

            DBItemLogWriter.getInstance().ConformTableColumns(conn, strTableName);
            this._DBManger.DBConns.PushDBConnection(conn);
            Console.WriteLine("正在初始化网络");
            this._TCPManager = TCPManager.getInstance();
            this._TCPManager.initialize((int)Global.GetSafeAttributeLong(xml, "Socket", "capacity"));
            this._TCPManager.DBMgr      = this._DBManger;
            this._TCPManager.RootWindow = this;
            this._TCPManager.Start(Global.GetSafeAttributeStr(xml, "Socket", "ip"), (int)Global.GetSafeAttributeLong(xml, "Socket", "port"));
            Console.WriteLine("正在配置后台线程");
            this.eventWorker                       = new BackgroundWorker();
            this.eventWorker.DoWork               += this.eventWorker_DoWork;
            this.ByDayCreateLogTableWorker         = new BackgroundWorker();
            this.ByDayCreateLogTableWorker.DoWork += new DoWorkEventHandler(this.ByDayCreateLogTableWorker_DoWork);
            this.MainDispatcherWorker              = new BackgroundWorker();
            this.MainDispatcherWorker.DoWork      += new DoWorkEventHandler(this.MainDispatcherWorker_DoWork);
            UnhandedException.ShowErrMsgBox        = false;
            GlobalServiceManager.initialize();
            GlobalServiceManager.startup();
            if (!this.MainDispatcherWorker.IsBusy)
            {
                this.MainDispatcherWorker.RunWorkerAsync();
            }
            if (!this.ByDayCreateLogTableWorker.IsBusy)
            {
                this.ByDayCreateLogTableWorker.RunWorkerAsync();
            }
            Console.WriteLine("系统启动完毕");
        }
예제 #24
0
		public int updateWanMoTaData(int nRoleID, string[] fields, int startIndex)
		{
			return WanMoTaDBController.updateWanMoTaData(TCPManager.getInstance().DBMgr, nRoleID, fields, 1);
		}
예제 #25
0
        /// <summary>
        /// This method is invoked when an asynchronous receive operation completes.
        /// If the remote host closed the connection, then the socket is closed.
        /// If data was received then the data is echoed back to the client.
        /// </summary>
        /// <param name="e">SocketAsyncEventArg associated with the completed receive operation.</param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            AsyncUserToken userToken = (e.UserToken as AsyncUserToken);
            TMSKSocket     s         = userToken.CurrentSocket;

            // Check if the remote host closed the connection.
            if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                // Increment the count of the total bytes receive by the server.
                Interlocked.Add(ref this.totalBytesRead, e.BytesTransferred);

                bool recvReturn = true;

                // Get the message received from the listener.
                //e.Buffer, e.Offset, e.bytesTransferred);
                //通知外部有新的socket到达
                if (null != SocketReceived)
                {
                    //字节排序
                    if (GameManager.FlagUseWin32Decrypt)
                    {
                        //使用动态库解密
                        int length = e.BytesTransferred;
                        unsafe
                        {
                            fixed(byte *p = e.Buffer)
                            {
                                Win32API.SortBytes(p, e.Offset, e.BytesTransferred, s.SortKey64);
                            }
                        }
                    }
                    else
                    {
                        // Win32API.SortBytes(e.Buffer, e.Offset, e.BytesTransferred, s.SortKey64);
                        DataHelper.SortBytes(e.Buffer, e.Offset, e.BytesTransferred, s.SortKey64);
                    }

                    try
                    {
                        recvReturn = SocketReceived(this, e);
                    }
                    catch (System.Exception ex)
                    {
                        SysConOut.WriteLine("接收数据异常" + ex.ToString());
                        //所有异常应当在下层捕获,不应抛到这层来
                        LogManager.WriteException(ex.ToString());
                        recvReturn = false;
                    }
                }

                if (recvReturn)
                {
                    //继续接收流程(以数据流为驱动)
                    Boolean willRaiseEvent = _ReceiveAsync(e);
                    if (!willRaiseEvent)
                    {
                        this.ProcessReceive(e);
                    }
                }
                else
                {
                    SysConOut.WriteLine("接收数据recvReturn = false");
                    UInt16 lastPacketCmd = TCPManager.getInstance().LastPacketCmdID(s);
                    string reason        = string.Format("CMD={0}", ((TCPGameServerCmds)lastPacketCmd).ToString());
                    this.CloseClientSocket(e, reason);
                }
            }
            else
            {
                SysConOut.WriteLine(string.Format("接收数据{0}--{1}", e.BytesTransferred, e.SocketError.ToString()));
                string reason = string.Format("[{0}]{1}", (int)e.SocketError, e.SocketError.ToString());
                this.CloseClientSocket(e, reason);
            }
        }