private void ConnectHandler(LNReq_Connect msg, PBChannel channel, int handle, uint seq) { if (!Enable) { LogSys.Log(LOG_TYPE.ERROR, "Connect to DataStorNode while DataOperator is Disable"); return; } try { bool ret = true; string errorMsg = string.Empty; LogSys.Log(LOG_TYPE.INFO, "DataStoreClient connect :{0} ", msg.ClientName); var reply = NLRep_Connect.CreateBuilder(); reply.SetResult(ret); reply.SetError(errorMsg); channel.Send(reply.Build()); } catch (Exception e) { var reply = NLRep_Connect.CreateBuilder(); reply.SetResult(false); reply.SetError(e.Message); channel.Send(reply.Build()); } }
private void LoadHandler(LNReq_Load msg, PBChannel channel, int handle, uint seq) { if (!Enable) { LogSys.Log(LOG_TYPE.ERROR, "Load a message while DataOperator is Disable"); return; } try { DataCacheSystem.Instance.LoadActionQueue.QueueAction((MyAction <uint, string, MyAction <DSLoadResult, string, IMessage> >)DataCacheSystem.Instance.Load, msg.DsMsgId, msg.Key, (ret, error, data) => { //这段代码必须保证线程安全,会在不同线程调用!!! var reply = NLRep_Load.CreateBuilder(); reply.SetDsMsgId(msg.DsMsgId); reply.SetKey(msg.Key); if (ret == DSLoadResult.Success) { reply.SetResult(NLRep_Load.Types.LoadResult.Success); reply.SetData(ByteString.Unsafe.FromBytes(channel_.Encode(data))); } else if (ret == DSLoadResult.Undone) { reply.SetResult(NLRep_Load.Types.LoadResult.Undone); reply.SetData(ByteString.Unsafe.FromBytes(channel_.Encode(data))); } else if (ret == DSLoadResult.NotFound) { reply.SetResult(NLRep_Load.Types.LoadResult.NotFound); reply.SetError(error); } else { reply.SetResult(NLRep_Load.Types.LoadResult.Error); reply.SetError(error); } NLRep_Load replyData = reply.Build(); channel.Send(replyData); LogSys.Log(LOG_TYPE.INFO, "Load data finished. msgId:({0}) key:({1}) result:({2}) ", msg.DsMsgId, msg.Key, ret); }); } catch (Exception e) { var errorReply = NLRep_Load.CreateBuilder(); errorReply.SetResult(NLRep_Load.Types.LoadResult.Error); errorReply.SetError(e.Message); channel.Send(errorReply.Build()); LogSys.Log(LOG_TYPE.ERROR, "DataStore load data failed. msgId:({0}) key:({1}) seq:({2}) error:({3} detail:{4})", msg.DsMsgId, msg.Key, seq, e.Message, e.StackTrace); } }
private void HandleReconnectUser(Msg_LR_ReconnectUser urMsg, PBChannel channel, int handle, uint seq) { bool isFieldThread; int ix = GetActiveRoomThreadIndex(urMsg.RoomID, out isFieldThread); if (ix < 0) { Msg_RL_ReplyReconnectUser replyBuilder = new Msg_RL_ReplyReconnectUser(); replyBuilder.UserGuid = urMsg.UserGuid; replyBuilder.RoomID = urMsg.RoomID; replyBuilder.Result = (int)Msg_RL_ReplyReconnectUser.ReconnectResultEnum.NotExist; channel.Send(replyBuilder); } else { if (isFieldThread) { RoomThread roomThread = field_roomthread_list_[ix]; roomThread.QueueAction(roomThread.HandleReconnectUser, urMsg, channel, handle, seq); } else { RoomThread roomThread = roomthread_list_[ix]; roomThread.QueueAction(roomThread.HandleReconnectUser, urMsg, channel, handle, seq); } } }
internal void HandleReconnectUser(Msg_LR_ReconnectUser urMsg, PBChannel channel, int handle, uint seq) { Msg_RL_ReplyReconnectUser.ReconnectResultEnum result; User us = GetUserByGuid(urMsg.UserGuid); if (null != us) { if ((int)UserControlState.UserDropped == us.UserControlState || !us.IsConnected()) { result = Msg_RL_ReplyReconnectUser.ReconnectResultEnum.Drop; } else { result = Msg_RL_ReplyReconnectUser.ReconnectResultEnum.Online; } } else { result = Msg_RL_ReplyReconnectUser.ReconnectResultEnum.NotExist; } Msg_RL_ReplyReconnectUser replyBuilder = new Msg_RL_ReplyReconnectUser(); replyBuilder.UserGuid = urMsg.UserGuid; replyBuilder.RoomID = urMsg.RoomID; replyBuilder.Result = (int)result; channel.Send(replyBuilder); }
private void DSConnectHandler(Msg_LD_Connect msg, PBChannel channel, int handle, uint seq) { try { LogSys.Log(LOG_TYPE.INFO, "DataStoreClient connect :{0} ", msg.ClientName); var reply = new Msg_DL_Connect(); reply.Result = true; reply.Error = string.Empty; channel.Send(reply); } catch (Exception e) { var reply = new Msg_DL_Connect(); reply.Result = false; reply.Error = e.Message; channel.Send(reply); LogSys.Log(LOG_TYPE.ERROR, "Connect failed. ClientName:{0}", msg.ClientName); } }
private void HandleUserQuit(Msg_LR_UserQuit msg, PBChannel channel, int handle, uint seq) { bool isFieldThread; int ix = GetActiveRoomThreadIndex(msg.RoomID, out isFieldThread); if (ix >= 0) { if (isFieldThread) { RoomThread roomThread = field_roomthread_list_[ix]; roomThread.QueueAction(roomThread.HandleUserQuit, msg, channel); } else { RoomThread roomThread = roomthread_list_[ix]; roomThread.QueueAction(roomThread.HandleUserQuit, msg, channel); } } else { Msg_RL_UserQuit replyBuilder = new Msg_RL_UserQuit(); replyBuilder.UserGuid = msg.UserGuid; replyBuilder.RoomID = msg.RoomID; channel.Send(replyBuilder); } }
private void ConnectHandler(LNReq_Connect msg, PBChannel channel, int handle, uint seq) { try { bool ret = true; string errorMsg = string.Empty; LogSys.Log(LOG_TYPE.INFO, "GMServerClient connect :{0} ", msg.ClientName); var reply = NLRep_Connect.CreateBuilder(); reply.SetResult(ret); reply.SetError(errorMsg); channel.Send(reply.Build()); } catch (Exception e) { var reply = NLRep_Connect.CreateBuilder(); reply.SetResult(false); reply.SetError(e.Message); channel.Send(reply.Build()); } }
internal void HandleReconnectUser(Msg_LR_ReconnectUser urMsg, PBChannel channel, int handle, uint seq) { bool ret = false; if (IsContainDroppedUser(urMsg.UserGuid)) { ret = true; } Msg_RL_ReplyReconnectUser.Builder replyBuilder = Msg_RL_ReplyReconnectUser.CreateBuilder(); replyBuilder.SetUserGuid(urMsg.UserGuid); replyBuilder.SetRoomID(urMsg.RoomID); replyBuilder.SetIsSuccess(ret); channel.Send(replyBuilder.Build()); }
private void SaveHandler(LNReq_Save msg, PBChannel channel, int handle, uint seq) { if (!Enable) { LogSys.Log(LOG_TYPE.ERROR, "Save a message while DataOperator is Disable"); return; } var reply = NLRep_Save.CreateBuilder(); reply.SetDsMsgId(msg.DsMsgId); reply.SetKey(msg.Key); reply.Result = NLRep_Save.Types.SaveResult.Success; try { byte[] data_bytes = ByteString.Unsafe.GetBuffer(msg.DsBytes); int calc_checksum = Crc32.Compute(data_bytes); if (msg.Checksum != calc_checksum) { throw new DataChecksumError(msg.Checksum, calc_checksum); } string dataTypeName = string.Empty; if (m_DSDMessages.TryGetValue(msg.DsMsgId, out dataTypeName)) { DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes); } else { dataTypeName = MessageMapping.Query(msg.DsMsgId).Name; if (dataTypeName.StartsWith("DSD_")) { //直接写入数据库 m_DSDMessages.AddOrUpdate(msg.DsMsgId, dataTypeName, (key, oldValue) => dataTypeName); DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes); } else { //写入数据缓存 DataCacheSystem.Instance.SaveActionQueue.QueueAction(DataCacheSystem.Instance.Save, msg.DsMsgId, msg.Key, data_bytes); } } } catch (Exception e) { reply.Result = NLRep_Save.Types.SaveResult.Error; reply.SetError(e.Message); LogSys.Log(LOG_TYPE.ERROR, "Save data ERROR: msgId:({0}) seq:({1}) error:({2}) detail:{3}", msg.DsMsgId, seq, e.Message, e.StackTrace); } channel.Send(reply.Build()); }
private void DSLoadHandler(Msg_LD_Load msg, PBChannel channel, int handle, uint seq) { try { DataCacheSystem.Instance.LoadActionQueue.QueueAction <Msg_LD_Load, PBChannel, int>(DataCacheSystem.Instance.Load, msg, channel, handle); } catch (Exception e) { var errorReply = new Msg_DL_LoadResult(); errorReply.MsgId = msg.MsgId; errorReply.PrimaryKeys.AddRange(msg.PrimaryKeys); errorReply.SerialNo = msg.SerialNo; errorReply.ErrorNo = Msg_DL_LoadResult.ErrorNoEnum.Exception; errorReply.ErrorInfo = e.Message; channel.Send(errorReply); LogSys.Log(LOG_TYPE.ERROR, "Load data failed. MsgId:{0}, Key:{1} Error:{2} Detail:{3}", msg.MsgId, msg.PrimaryKeys, e.Message, e.StackTrace); } }
internal void HandleUserQuit(Msg_LR_UserQuit msg, PBChannel channel) { Room room = GetRoomByID(msg.RoomID); if (null != room) { User user = room.GetUserByGuid(msg.UserGuid); if (null != user) { room.DeleteUser(user); } } Msg_RL_UserQuit replyBuilder = new Msg_RL_UserQuit(); replyBuilder.UserGuid = msg.UserGuid; replyBuilder.RoomID = msg.RoomID; channel.Send(replyBuilder); }
private void HandleReconnectUser(Msg_LR_ReconnectUser urMsg, PBChannel channel, int handle, uint seq) { int ix = GetActiveRoomThreadIndex(urMsg.RoomID); if (ix < 0) { Msg_RL_ReplyReconnectUser.Builder replyBuilder = Msg_RL_ReplyReconnectUser.CreateBuilder(); replyBuilder.SetUserGuid(urMsg.UserGuid); replyBuilder.SetRoomID(urMsg.RoomID); replyBuilder.SetIsSuccess(false); channel.Send(replyBuilder.Build()); } else { RoomThread roomThread = roomthread_list_[ix]; roomThread.QueueAction(roomThread.HandleReconnectUser, urMsg, channel, handle, seq); } }
private void RemoveUserForChangeScene(Room room, User user, ulong userGuid, int roomId, int targetRoomId, PBChannel channel, int handle, uint seq) { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); EntityInfo info = user.Info; if (null != info) { replyBuilder.HP = info.Hp; replyBuilder.MP = info.Energy; } room.RemoveUserFromRoomThread(user, true); replyBuilder.UserGuid = userGuid; replyBuilder.RoomID = roomId; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Success; channel.Send(replyBuilder); }
private void DSSaveHandler(Msg_LD_Save msg, PBChannel channel, int handle, uint seq) { var saveResult = new Msg_DL_SaveResult(); saveResult.MsgId = msg.MsgId; saveResult.PrimaryKeys.AddRange(msg.PrimaryKeys); saveResult.SerialNo = msg.SerialNo; saveResult.ErrorNo = Msg_DL_SaveResult.ErrorNoEnum.Success; saveResult.ErrorInfo = string.Empty; try { //写入数据缓存 //TODO:是否将byte[]解析出protobuf对象? 提前反序列化成对象的好处:1.若数据有错误,反序列化失败,可反馈给lobby;2.protobuf对象可重用? //TODO:解析primaryKey和foreignKey DataCacheSystem.Instance.SaveActionQueue.QueueAction(DataCacheSystem.Instance.Save, msg.MsgId, msg.PrimaryKeys, msg.ForeignKeys, msg.Data, msg.SerialNo); } catch (Exception e) { saveResult.ErrorNo = Msg_DL_SaveResult.ErrorNoEnum.PostError; saveResult.ErrorInfo = e.Message; LogSys.Log(LOG_TYPE.ERROR, "Save data ERROR: MsgId:{0}, Key:{1}, Error:{2}, Detail:{3}", msg.MsgId, msg.PrimaryKeys, e.Message, e.StackTrace); } channel.Send(saveResult); }
private void VerifyAccountWorker(LB_VerifyAccount msg, PBChannel channel) { try { int tag = CreateTag(); string signParam = string.Format("{0}{1}{2}{3}{4}{5}", msg.OpCode, msg.Data, m_AppKey, m_AppSecret, tag, msg.ChannelId); string sign = CreateSign(signParam); HttpClient client = new HttpClient(); client.Timeout = m_HttpRequestTimeout; HttpPost postMethod = new HttpPost(new Uri(m_TestBillingServerUrl)); postMethod.Headers.Add("appkey", m_AppKey); postMethod.Headers.Add("sign", sign); postMethod.Headers.Add("tag", tag.ToString()); postMethod.Headers.Add("opcode", msg.OpCode.ToString()); postMethod.Headers.Add("channelId", msg.ChannelId.ToString()); List <NameValuePair> nameValuePairList = new List <NameValuePair>(); nameValuePairList.Add(new NameValuePair("data", msg.Data)); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Encoding.UTF8); postMethod.Entity = formEntity; LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost headers. appkey:{1}, sign:{2}, tag:{3}, opcode:{4}, channelId:{5}", msg.Account, m_AppKey, sign, tag, msg.OpCode, msg.ChannelId); LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost parameters. data:{1}", msg.Account, msg.Data); //============================================ HttpResponse response = client.Execute(postMethod); string responseStr = EntityUtils.ToString(response.Entity); DestroyTag(tag); //================================================== LogSys.Log(LOG_TYPE.INFO, "Account:{0}, Response:{1}", msg.Account, responseStr); //================================================== JsonVerifyAccountResult result = JsonConvert.DeserializeObject(responseStr, typeof(JsonVerifyAccountResult)) as JsonVerifyAccountResult; var reply = BL_VerifyAccountResult.CreateBuilder(); reply.Account = msg.Account; reply.OpCode = result.opcode; reply.ChannelId = result.channelId; reply.AccountId = ""; reply.Result = false; int repState = result.state; if (repState == (int)BillingRepState.Success && result.data != null) { int status = int.Parse(result.data.status); if (status == 1 && result.channelId == msg.ChannelId && result.opcode == msg.OpCode) { reply.AccountId = result.data.userid; reply.Result = true; } } if (reply.Result == true) { LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Green, "Account verify success. Account:{0} ID:{1}", reply.Account, reply.AccountId); } else { LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Yellow, "Account verify failed. Account:{0} Msg:{1}", reply.Account, result.error); } channel.Send(reply.Build()); } catch (Exception ex) { LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception Type:{0}", ex.GetType().ToString()); LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception:{0}\n{1}", ex.Message, ex.StackTrace); } }
//-------------------------------------- private void HandleCreateBattleRoom(Msg_LR_CreateBattleRoom createRoomMsg, PBChannel channel, int handle, uint seq) { LogSys.Log(LOG_TYPE.DEBUG, "channel:{0}, seq:{1}", channel, seq); bool canContinue = true; //先检查是否玩家已经在room上。 foreach (Msg_LR_RoomUserInfo rui in createRoomMsg.UsersList) { if (RoomPeerMgr.Instance.IsKeyExist(rui.Key)) { canContinue = false; LogSys.Log(LOG_TYPE.WARN, "User is already in room. UserGuid:{0}, Key:{1}", rui.Guid, rui.Key); break; } } if (!canContinue) { Msg_RL_ReplyCreateBattleRoom.Builder replyBuilder0 = Msg_RL_ReplyCreateBattleRoom.CreateBuilder(); replyBuilder0.SetRoomId(createRoomMsg.RoomId); replyBuilder0.SetIsSuccess(false); channel.Send(replyBuilder0.Build()); return; } List <User> users = new List <User>(); foreach (Msg_LR_RoomUserInfo rui in createRoomMsg.UsersList) { User rsUser = user_pool_.NewUser(); LogSys.Log(LOG_TYPE.INFO, "NewUser {0} for {1} {2}", rsUser.LocalID, rui.Guid, rui.Key); rsUser.Init(); if (!rsUser.SetKey(rui.Key)) { LogSys.Log(LOG_TYPE.WARN, "user who's key is {0} already in room!", rui.Key); LogSys.Log(LOG_TYPE.INFO, "FreeUser {0} for {1} {2}, [RoomManager.HandleCreateBattleRoom]", rsUser.LocalID, rui.Guid, rui.Key); user_pool_.FreeUser(rsUser.LocalID); continue; } rsUser.Guid = rui.Guid; rsUser.Name = rui.Nick; rsUser.HeroId = rui.Hero; rsUser.CampId = rui.Camp; rsUser.Level = rui.Level; rsUser.ArgFightingScore = rui.ArgScore; if (rui.IsMachine == true) { rsUser.UserControlState = (int)UserControlState.Ai; } else { rsUser.UserControlState = (int)UserControlState.User; } //装备数据 for (int index = 0; index < rui.ShopEquipmentsIdCount; ++index) { rsUser.ShopEquipmentsId.Add(rui.GetShopEquipmentsId(index)); } if (null != rsUser.Skill) { rsUser.Skill.Clear(); for (int i = 0; i < rui.SkillsCount; i++) { SkillTransmitArg skill_arg = new SkillTransmitArg(); skill_arg.SkillId = rui.SkillsList[i].SkillId; skill_arg.SkillLevel = rui.SkillsList[i].SkillLevel; rsUser.Skill.Add(skill_arg); } if (rui.HasPresetIndex) { rsUser.PresetIndex = rui.PresetIndex; } } /// if (null != rsUser.Equip) { rsUser.Equip.Clear(); for (int i = 0; i < rui.EquipsCount; i++) { ItemTransmitArg equip_arg = new ItemTransmitArg(); equip_arg.ItemId = rui.EquipsList[i].EquipId; equip_arg.ItemLevel = rui.EquipsList[i].EquipLevel; equip_arg.ItemRandomProperty = rui.EquipsList[i].EquipRandomProperty; rsUser.Equip.Add(equip_arg); } } /// if (null != rsUser.Legacy) { rsUser.Legacy.Clear(); for (int i = 0; i < rui.LegacysCount; i++) { ItemTransmitArg legacy_arg = new ItemTransmitArg(); legacy_arg.ItemId = rui.LegacysList[i].LegacyId; legacy_arg.ItemLevel = rui.LegacysList[i].LegacyLevel; legacy_arg.ItemRandomProperty = rui.LegacysList[i].LegacyRandomProperty; legacy_arg.IsUnlock = rui.LegacysList[i].LegacyIsUnlock; rsUser.Legacy.Add(legacy_arg); } } /// if (null != rsUser.XSouls) { rsUser.XSouls.GetAllXSoulPartData().Clear(); for (int i = 0; i < rui.XSoulsCount; i++) { ItemDataInfo item = new ItemDataInfo(); item.ItemId = rui.XSoulsList[i].ItemId; item.Level = rui.XSoulsList[i].Level; item.Experience = rui.XSoulsList[i].Experience; ItemConfig configer = ItemConfigProvider.Instance.GetDataById(item.ItemId); item.ItemConfig = configer; if (configer != null) { XSoulPartInfo part_info = new XSoulPartInfo((XSoulPart)configer.m_WearParts, item); part_info.ShowModelLevel = rui.XSoulsList[i].ModelLevel; rsUser.XSouls.SetXSoulPartData((XSoulPart)configer.m_WearParts, part_info); } } } // partner if (null != rui.Partner) { PartnerConfig partnerConfig = PartnerConfigProvider.Instance.GetDataById(rui.Partner.PartnerId); if (null != partnerConfig) { PartnerInfo partnerInfo = new PartnerInfo(partnerConfig); partnerInfo.CurAdditionLevel = rui.Partner.PartnerLevel; partnerInfo.CurSkillStage = rui.Partner.PartnerStage; rsUser.Partner = partnerInfo; } } users.Add(rsUser); LogSys.Log(LOG_TYPE.DEBUG, "enter room {0} scene {1} user info guid={2}, name={3}, key={4}, camp={5}", createRoomMsg.RoomId, createRoomMsg.SceneType, rui.Guid, rui.Nick, rui.Key, rui.Camp); } //临时测试人机机制 /* * Data_SceneConfig sceneCfg = SceneConfigProvider.Instance.GetSceneConfigById(createRoomMsg.SceneType); * if (1 == createRoomMsg.UsersCount && null != sceneCfg && sceneCfg.m_Type == (int)SceneTypeEnum.TYPE_PVP) { * for (int i = 0; i < 9; ++i) { * User rsUser = room_mgr_.NewUser(); * rsUser.Init(); * rsUser.SetKey(0xffffffff); * rsUser.Guid = 0xffffffff; * rsUser.Name = "Computer" + i; * rsUser.HeroId = CrossEngineHelper.Random.Next(1, 3); * rsUser.CampId = (i < 4 ? (int)CampIdEnum.Blue : (int)CampIdEnum.Red); * rsUser.UserControlState = (int)UserControlState.Ai; * users.Add(rsUser); * LogSys.Log(LOG_TYPE.DEBUG, "Computer enter room"); * } * } */ bool ret = false; if (users.Count == 0) { LogSys.Log(LOG_TYPE.WARN, "no user enter room"); ret = false; } else { ret = ActiveRoom(createRoomMsg.RoomId, createRoomMsg.SceneType, users.ToArray()); } if (ret) { LogSys.Log(LOG_TYPE.DEBUG, "user enter room success."); } else { LogSys.Log(LOG_TYPE.DEBUG, "user enter room failed!"); } Msg_RL_ReplyCreateBattleRoom.Builder replyBuilder = Msg_RL_ReplyCreateBattleRoom.CreateBuilder(); replyBuilder.SetRoomId(createRoomMsg.RoomId); replyBuilder.SetIsSuccess(ret); channel.Send(replyBuilder.Build()); }
//==========================通过QueueAction调用的方法=========================================== //注意!回调函数目前在缓存线程与db线程都可能调用,回调函数的实现需要是线程安全的(目前一般都是发消息,满足此条件)。 internal void Load(Msg_LD_Load msg, PBChannel channel, int handle) { //首先在缓存中查找数据,若未找到,则到DB中查找 bool isLoadCache = true; Msg_DL_LoadResult ret = new Msg_DL_LoadResult(); ret.MsgId = msg.MsgId; ret.PrimaryKeys.AddRange(msg.PrimaryKeys); ret.SerialNo = msg.SerialNo; ret.ErrorNo = 0; for (int i = 0; i < msg.LoadRequests.Count; ++i) { Msg_LD_SingleLoadRequest req = msg.LoadRequests[i]; KeyString loadKey = KeyString.Wrap(req.Keys); switch (req.LoadType) { case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadAll: { isLoadCache = false; } break; case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadSingle: { InnerCacheItem item = m_InnerCacheSystem.Find(req.MsgId, loadKey); if (item != null) { Msg_DL_SingleRowResult result = new Msg_DL_SingleRowResult(); result.MsgId = req.MsgId; result.PrimaryKeys.AddRange(req.Keys); result.DataVersion = 0; //TODO: 这个DataVersion有用吗? result.Data = item.DataMessage; ret.Results.Add(result); } else { isLoadCache = false; } } break; case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadMulti: { List <InnerCacheItem> itemList = m_InnerCacheSystem.FindByForeignKey(req.MsgId, loadKey); foreach (var item in itemList) { Msg_DL_SingleRowResult result = new Msg_DL_SingleRowResult(); result.MsgId = req.MsgId; result.PrimaryKeys.AddRange(req.Keys); result.DataVersion = 0; //TODO: 这个DataVersion有用吗? result.Data = item.DataMessage; ret.Results.Add(result); } } break; } } if (isLoadCache) { channel.Send(ret); LogSys.Log(LOG_TYPE.INFO, "Load data from cache. MsgId:{0}, Key:{1}", msg.MsgId, KeyString.Wrap(msg.PrimaryKeys).ToString()); } else { //查找DB交给DBLoad线程操作 DbThreadManager.Instance.LoadActionQueue.QueueAction(DataLoadImplement.Load, msg, (MyAction <Msg_DL_LoadResult>)((Msg_DL_LoadResult result) => { if (result.ErrorNo == Msg_DL_LoadResult.ErrorNoEnum.Success) { foreach (Msg_DL_SingleRowResult row in result.Results) { m_InnerCacheSystem.AddOrUpdate(row.MsgId, KeyString.Wrap(row.PrimaryKeys), KeyString.Wrap(row.ForeignKeys), row.Data); } } channel.Send(result); LogSys.Log(LOG_TYPE.INFO, "Load data from database. MsgId:{0}, Key:{1}", msg.MsgId, KeyString.Wrap(msg.PrimaryKeys).ToString()); })); } }
//-------------------------------------- private void HandleEnterScene(Msg_LR_EnterScene msg, PBChannel channel, int handle, uint seq) { ulong guid = msg.UserGuid; int roomId = msg.RoomID; bool isFieldThread; int ix = GetActiveRoomThreadIndex(roomId, out isFieldThread); if (ix < 0) { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } else { RoomThread roomThread; if (isFieldThread) { roomThread = field_roomthread_list_[ix]; } else { roomThread = roomthread_list_[ix]; } Msg_LR_RoomUserInfo rui = msg.UserInfo; User rsUser = user_pool_.NewUser(); LogSys.Log(LOG_TYPE.INFO, "NewUser {0} for {1} {2}", rsUser.LocalID, rui.Guid, rui.Key); rsUser.Init(); if (!rsUser.SetKey(rui.Key)) { LogSys.Log(LOG_TYPE.WARN, "user who's key is {0} already in room!", rui.Key); LogSys.Log(LOG_TYPE.INFO, "FreeUser {0} for {1} {2}, [RoomManager.HandleEnterScene]", rsUser.LocalID, rui.Guid, rui.Key); user_pool_.FreeUser(rsUser.LocalID); Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.User_Key_Exist; channel.Send(replyBuilder); } else { rsUser.LobbyUserData = rui; if (rui.IsMachine == true) { rsUser.UserControlState = (int)UserControlState.Ai; } else { rsUser.UserControlState = (int)UserControlState.User; } if (msg.HP > 0 && msg.MP > 0) { rsUser.SetHpArmor(msg.HP, msg.MP); } if (rui.EnterX > 0 && rui.EnterY > 0) { rsUser.SetEnterPoint(rui.EnterX, rui.EnterY); } roomThread.QueueAction(roomThread.AddUser, rsUser, roomId, (MyAction <bool, int, User>)((bool success, int sceneId, User user) => { if (success) { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Success; channel.Send(replyBuilder); } else { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } } }
//-------------------------------------- private void HandleEnterScene(Msg_LR_EnterScene msg, PBChannel channel, int handle, uint seq) { ulong guid = msg.UserGuid; int roomId = msg.RoomID; bool isFieldThread; int ix = GetActiveRoomThreadIndex(roomId, out isFieldThread); if (ix < 0) { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } else { RoomThread roomThread; if (isFieldThread) { roomThread = field_roomthread_list_[ix]; } else { roomThread = roomthread_list_[ix]; } Msg_LR_RoomUserInfo rui = msg.UserInfo; User rsUser = user_pool_.NewUser(); LogSys.Log(LOG_TYPE.INFO, "NewUser {0} for {1} {2}", rsUser.LocalID, rui.Guid, rui.Key); rsUser.Init(); if (!rsUser.SetKey(rui.Key)) { LogSys.Log(LOG_TYPE.WARN, "user who's key is {0} already in room!", rui.Key); LogSys.Log(LOG_TYPE.INFO, "FreeUser {0} for {1} {2}, [RoomManager.HandleEnterScene]", rsUser.LocalID, rui.Guid, rui.Key); user_pool_.FreeUser(rsUser.LocalID); Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.User_Key_Exist; channel.Send(replyBuilder); } else { rsUser.LobbyUserData = rui; if (rui.IsMachine == true) rsUser.UserControlState = (int)UserControlState.Ai; else rsUser.UserControlState = (int)UserControlState.User; if (msg.HP > 0 && msg.MP > 0) { rsUser.SetHpArmor(msg.HP, msg.MP); } if (rui.EnterX > 0 && rui.EnterY > 0) { rsUser.SetEnterPoint(rui.EnterX, rui.EnterY); } roomThread.QueueAction(roomThread.AddUser, rsUser, roomId, (MyAction<bool, int, User>)((bool success, int sceneId, User user) => { if (success) { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Success; channel.Send(replyBuilder); } else { Msg_RL_EnterSceneResult replyBuilder = new Msg_RL_EnterSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } } }
private void HandleChangeScene(Msg_LR_ChangeScene msg, PBChannel channel, int handle, uint seq) { ulong guid = msg.UserGuid; int roomid = msg.RoomID; int targetRoomId = msg.TargetRoomID; bool isFieldThread; int ix = GetActiveRoomThreadIndex(msg.RoomID, out isFieldThread); if (ix < 0) { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = msg.UserGuid; replyBuilder.RoomID = msg.RoomID; replyBuilder.TargetRoomID = msg.TargetRoomID; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } else { RoomThread roomThread; if (isFieldThread) { roomThread = field_roomthread_list_[ix]; } else { roomThread = roomthread_list_[ix]; } bool targetIsFieldThread; int targetIx = GetActiveRoomThreadIndex(targetRoomId, out targetIsFieldThread); if (null != roomThread) { if (targetIx >= 0) { //同服切场景 roomThread.QueueAction(roomThread.RemoveUser, guid, roomid, false, (MyAction <bool, int, User>)((bool success, int sceneId, User user) => { if (success) { PlayerGotoRoom(user, roomid, targetRoomId); } else { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } else { //跨服切场景 roomThread.QueueAction(roomThread.RemoveUser, guid, roomid, true, (MyAction <bool, int, User>)((bool success, int sceneId, User user) => { if (success) { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); EntityInfo info = user.Info; if (null != info) { replyBuilder.HP = info.Hp; replyBuilder.MP = info.Energy; } replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Success; channel.Send(replyBuilder); } else { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } } } }
private void VerifyAccountWorkerWithHttpRequest(LB_VerifyAccount msg, PBChannel channel) { HttpWebRequest myHttpWebRequest = null; HttpWebResponse myHttpWebResponse = null; try { int tag = CreateTag(); string signParam = string.Format("{0}{1}{2}{3}{4}{5}", msg.OpCode, msg.Data, m_AppKey, m_AppSecret, tag, msg.ChannelId); string sign = CreateSign(signParam); IDictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("appkey", m_AppKey); headers.Add("sign", sign); headers.Add("tag", tag.ToString()); headers.Add("opcode", msg.OpCode.ToString()); headers.Add("channelId", msg.ChannelId.ToString()); IDictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("data", msg.Data); LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost headers. appkey:{1}, sign:{2}, tag:{3}, opcode:{4}, channelId:{5}", msg.Account, m_AppKey, sign, tag, msg.OpCode, msg.ChannelId); LogSys.Log(LOG_TYPE.INFO, "Account:{0}, HttpPost parameters. data:{1}", msg.Account, msg.Data); //============================================ myHttpWebRequest = HttpWebUtility.CreatePostHttpRequest(m_TestBillingServerUrl, headers, parameters, m_HttpRequestTimeout); myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); string responseStr = string.Empty; using (Stream streamResponse = myHttpWebResponse.GetResponseStream()) { using (StreamReader readStream = new StreamReader(streamResponse, Encoding.UTF8)) { responseStr = readStream.ReadToEnd(); readStream.Close(); } streamResponse.Flush(); streamResponse.Close(); } DestroyTag(tag); //================================================== LogSys.Log(LOG_TYPE.INFO, "Account:{0}, Response:{1}", msg.Account, responseStr); //================================================== JsonVerifyAccountResult result = JsonConvert.DeserializeObject(responseStr, typeof(JsonVerifyAccountResult)) as JsonVerifyAccountResult; var reply = BL_VerifyAccountResult.CreateBuilder(); reply.Account = msg.Account; reply.OpCode = result.opcode; reply.ChannelId = result.channelId; reply.AccountId = ""; reply.Result = false; int repState = result.state; if (repState == (int)BillingRepState.Success && result.data != null) { int status = int.Parse(result.data.status); if (status == 1 && result.channelId == msg.ChannelId && result.opcode == msg.OpCode) { reply.AccountId = result.data.userid; reply.Result = true; } } if (reply.Result == true) { LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Green, "Account verify success. Account:{0} ID:{1}", reply.Account, reply.AccountId); } else { LogSys.Log(LOG_TYPE.INFO, ConsoleColor.Yellow, "Account verify failed. Account:{0} Msg:{1}", reply.Account, result.error); } channel.Send(reply.Build()); } catch (Exception ex) { LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception Type:{0}", ex.GetType().ToString()); LogSys.Log(LOG_TYPE.ERROR, ConsoleColor.Red, "Exception:{0}\n{1}", ex.Message, ex.StackTrace); } finally { if (myHttpWebResponse != null) { myHttpWebResponse.Close(); } if (myHttpWebRequest != null) { myHttpWebRequest.Abort(); } } }
private void DSLoadHandler(Msg_LD_Load msg, PBChannel channel, int handle, uint seq) { try { DataCacheSystem.Instance.LoadActionQueue.QueueAction<Msg_LD_Load, PBChannel, int>(DataCacheSystem.Instance.Load, msg, channel, handle); } catch (Exception e) { var errorReply = new Msg_DL_LoadResult(); errorReply.MsgId = msg.MsgId; errorReply.PrimaryKeys.AddRange(msg.PrimaryKeys); errorReply.SerialNo = msg.SerialNo; errorReply.ErrorNo = Msg_DL_LoadResult.ErrorNoEnum.Exception; errorReply.ErrorInfo = e.Message; channel.Send(errorReply); LogSys.Log(LOG_TYPE.ERROR, "Load data failed. MsgId:{0}, Key:{1} Error:{2} Detail:{3}", msg.MsgId, msg.PrimaryKeys, e.Message, e.StackTrace); } }
private void HandleChangeScene(Msg_LR_ChangeScene msg, PBChannel channel, int handle, uint seq) { ulong guid = msg.UserGuid; int roomid = msg.RoomID; int targetRoomId = msg.TargetRoomID; bool isFieldThread; int ix = GetActiveRoomThreadIndex(msg.RoomID, out isFieldThread); if (ix < 0) { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = msg.UserGuid; replyBuilder.RoomID = msg.RoomID; replyBuilder.TargetRoomID = msg.TargetRoomID; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } else { RoomThread roomThread; if (isFieldThread) { roomThread = field_roomthread_list_[ix]; } else { roomThread = roomthread_list_[ix]; } bool targetIsFieldThread; int targetIx = GetActiveRoomThreadIndex(targetRoomId, out targetIsFieldThread); if (null != roomThread) { if (targetIx >= 0) { //ͬ���г��� roomThread.QueueAction(roomThread.RemoveUser, guid, roomid, false, (MyAction<bool, int, User>)((bool success, int sceneId, User user) => { if (success) { PlayerGotoRoom(user, roomid, targetRoomId); } else { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } else { //����г��� roomThread.QueueAction(roomThread.RemoveUser, guid, roomid, true, (MyAction<bool, int, User>)((bool success, int sceneId, User user) => { if (success) { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); EntityInfo info = user.Info; if (null != info) { replyBuilder.HP = info.Hp; replyBuilder.MP = info.Energy; } replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Success; channel.Send(replyBuilder); } else { Msg_RL_ChangeSceneResult replyBuilder = new Msg_RL_ChangeSceneResult(); replyBuilder.UserGuid = guid; replyBuilder.RoomID = roomid; replyBuilder.TargetRoomID = targetRoomId; replyBuilder.Result = (int)SceneOperationResultEnum.Cant_Find_Room; channel.Send(replyBuilder); } })); } } } }
//==========================通过QueueAction调用的方法=========================================== //注意!回调函数目前在缓存线程与db线程都可能调用,回调函数的实现需要是线程安全的(目前一般都是发消息,满足此条件)。 internal void Load(Msg_LD_Load msg, PBChannel channel, int handle) { //首先在缓存中查找数据,若未找到,则到DB中查找 bool isLoadCache = true; Msg_DL_LoadResult ret = new Msg_DL_LoadResult(); ret.MsgId = msg.MsgId; ret.PrimaryKeys.AddRange(msg.PrimaryKeys); ret.SerialNo = msg.SerialNo; ret.ErrorNo = 0; for (int i = 0; i < msg.LoadRequests.Count; ++i) { Msg_LD_SingleLoadRequest req = msg.LoadRequests[i]; KeyString loadKey = KeyString.Wrap(req.Keys); switch (req.LoadType) { case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadAll: { isLoadCache = false; } break; case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadSingle: { InnerCacheItem item = m_InnerCacheSystem.Find(req.MsgId, loadKey); if (item != null) { Msg_DL_SingleRowResult result = new Msg_DL_SingleRowResult(); result.MsgId = req.MsgId; result.PrimaryKeys.AddRange(req.Keys); result.DataVersion = 0; //TODO: 这个DataVersion有用吗? result.Data = item.DataMessage; ret.Results.Add(result); } else { isLoadCache = false; } } break; case Msg_LD_SingleLoadRequest.LoadTypeEnum.LoadMulti: { List<InnerCacheItem> itemList = m_InnerCacheSystem.FindByForeignKey(req.MsgId, loadKey); foreach (var item in itemList) { Msg_DL_SingleRowResult result = new Msg_DL_SingleRowResult(); result.MsgId = req.MsgId; result.PrimaryKeys.AddRange(req.Keys); result.DataVersion = 0; //TODO: 这个DataVersion有用吗? result.Data = item.DataMessage; ret.Results.Add(result); } } break; } } if (isLoadCache) { channel.Send(ret); LogSys.Log(LOG_TYPE.INFO, "Load data from cache. MsgId:{0}, Key:{1}", msg.MsgId, KeyString.Wrap(msg.PrimaryKeys).ToString()); } else { //查找DB交给DBLoad线程操作 DbThreadManager.Instance.LoadActionQueue.QueueAction(DataLoadImplement.Load, msg, (MyAction<Msg_DL_LoadResult>)((Msg_DL_LoadResult result) => { if (result.ErrorNo == Msg_DL_LoadResult.ErrorNoEnum.Success) { foreach (Msg_DL_SingleRowResult row in result.Results) { m_InnerCacheSystem.AddOrUpdate(row.MsgId, KeyString.Wrap(row.PrimaryKeys), KeyString.Wrap(row.ForeignKeys), row.Data); } } channel.Send(result); LogSys.Log(LOG_TYPE.INFO, "Load data from database. MsgId:{0}, Key:{1}", msg.MsgId, KeyString.Wrap(msg.PrimaryKeys).ToString()); })); } }