/// <summary> /// Loads all packet handlers in the code base. /// </summary> private static IPacketHandler[] GetHandlers() { try { var max = ((Packet[])Enum.GetValues(typeof(Packet))).Select(x => (byte)x).Max(); var handlers = new IPacketHandler[max]; //Load all instances of IPacketHandler var type = typeof(IPacketHandler); foreach (var messageType in typeof(PacketProcessor).Assembly .GetTypesLoaded() .Where(x => type.IsAssignableFrom(x) && x != type && !x.IsAbstract) ) { var handler = (IPacketHandler)Activator.CreateInstance(messageType); handlers[(int)handler.PacketId] = handler; } return handlers; } catch (Exception e) { ProgramLog.Log(e, "Failed to collect all packet handlers"); return null; } }
public void Request(PacketManager.PacketID packetId, IPacketHandler packet) { if (PacketProcessor != null) { if (PacketProcessor.ContainsKey(packetId) == true) { PacketProcessor[packetId](); } else { Debug.Log(packetId + " NO Support in Server"); } if ( packetId == PacketManager.PacketID.QUEST_FINISH || packetId == PacketManager.PacketID.CHAR_BUYING || packetId == PacketManager.PacketID.CHAR_UPGRADE || packetId == PacketManager.PacketID.PARTY_MEMBER_CHARNGE || packetId == PacketManager.PacketID.REFRESH_POSTBOXGIFT) { Save(); } } }
public HandlerMethodReference(Action<object, object> handlerMethod, IPacketHandler parentHandler, PacketAttribute handlerMethodAttribute) { HandlerMethod = handlerMethod; ParentHandler = parentHandler; HandlerMethodAttribute = handlerMethodAttribute; Identification = HandlerMethodAttribute.Header; PassNonParseablePacket = false; }
public HandlerMethodReference(Action<object, object> handlerMethod, IPacketHandler parentHandler, Type packetBaseParameterType) { HandlerMethod = handlerMethod; ParentHandler = parentHandler; PacketDefinitionParameterType = packetBaseParameterType; PacketHeaderAttribute headerAttribute = ((PacketHeaderAttribute)PacketDefinitionParameterType.GetCustomAttributes(true).FirstOrDefault(ca => ca.GetType().Equals(typeof(PacketHeaderAttribute)))); Identification = headerAttribute?.Identification; PassNonParseablePacket = headerAttribute?.PassNonParseablePacket ?? false; }
void RegisterHandler(RecvOps opcode, IPacketHandler handler) { short op = (short)opcode; try { handlers[op] = handler; } catch (Exception) { Console.WriteLine("Error registering packet handler " + Enum.GetName(typeof(RecvOps), op)); } }
/// <summary> /// /// </summary> /// <param name="code"></param> /// <param name="handler"></param> /// <returns></returns> private static bool RegisterPacketHandler(int code, IPacketHandler handler) { IPacketHandler test = null; _packetHandlers.TryGetValue(code, out test); if (test != null) { Console.WriteLine("Packet handler " + code + " already exists."); return false; } _packetHandlers[code] = handler; return true; }
public void registerHandler(IPacketHandler handler, PacketCmdC2S pktcmd, Channel channel) { if (!_handlerTable.ContainsKey(pktcmd)) _handlerTable.Add(pktcmd, new Dictionary<Channel, IPacketHandler>()); var dict = _handlerTable[pktcmd]; if (!dict.ContainsKey(channel)) dict.Add(channel, handler); else dict[channel] = handler; }
public override void Handle(GameSession session, PacketReader packet) { BankMode mode = (BankMode)packet.ReadByte(); switch (mode) { case BankMode.House: HandleOpen(session, TimeInfo.Now()); break; case BankMode.Inventory: HandleOpen(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { SuperChatMode mode = (SuperChatMode)packet.ReadByte(); switch (mode) { case SuperChatMode.Select: HandleSelect(session, packet); break; case SuperChatMode.Deselect: HandleDeselect(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { UserEnvMode mode = (UserEnvMode)packet.ReadByte(); switch (mode) { case UserEnvMode.Change: HandleTitleChange(session, packet); break; case UserEnvMode.Achieve: HandleAchieve(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { BuildModeMode mode = (BuildModeMode)packet.ReadByte(); switch (mode) { case BuildModeMode.Stop: HandleStop(session); break; case BuildModeMode.Start: HandleStart(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { InteractObjectMode mode = (InteractObjectMode)packet.ReadByte(); switch (mode) { case InteractObjectMode.Cast: HandleCast(session, packet); break; case InteractObjectMode.Interact: HandleInteract(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { RequestMoveFieldMode mode = (RequestMoveFieldMode)packet.ReadByte(); switch (mode) { case RequestMoveFieldMode.Move: HandleMove(session, packet); break; case RequestMoveFieldMode.LeaveInstance: HandleLeaveInstance(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { RequestGemEquipmentMode mode = (RequestGemEquipmentMode)packet.ReadByte(); switch (mode) { case RequestGemEquipmentMode.EquipItem: HandleEquipItem(session, packet); break; case RequestGemEquipmentMode.UnequipItem: HandleUnequipItem(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { ItemEquipMode function = (ItemEquipMode)packet.ReadByte(); switch (function) { case ItemEquipMode.Equip: HandleEquipItem(session, packet); break; case ItemEquipMode.Unequip: HandleUnequipItem(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(function); break; } }
public override void Handle(GameSession session, PacketReader packet) { QuitMode mode = (QuitMode)packet.ReadByte(); switch (mode) { case QuitMode.ChangeCharacter: HandleChangeCharacter(session); break; case QuitMode.Quit: HandleQuit(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { StatPointMode mode = (StatPointMode)packet.ReadByte(); switch (mode) { case StatPointMode.Increment: HandleStatIncrement(session, packet); break; case StatPointMode.Reset: HandleResetStatDistribution(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { RequestHomeMode mode = (RequestHomeMode)packet.ReadByte(); switch (mode) { case RequestHomeMode.InviteToHome: HandleInviteToHome(session, packet); break; case RequestHomeMode.MoveToHome: HandleMoveToHome(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { ShopMode mode = (ShopMode)packet.ReadByte(); switch (mode) { case ShopMode.ViaItem: HandleViaItem(session, packet); break; case ShopMode.Arena: HandleMapleArenaShop(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { TriggerMode mode = (TriggerMode)packet.ReadByte(); switch (mode) { case TriggerMode.SkipCutscene: HandleSkipCutscene(session); break; case TriggerMode.UpdateWidget: HandleUpdateWidget(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { EmoteMode mode = (EmoteMode)packet.ReadByte(); switch (mode) { case EmoteMode.LearnEmote: HandleLearnEmote(session, packet); break; case EmoteMode.UseEmote: HandleUseEmote(packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { TrophyHandlerMode mode = (TrophyHandlerMode)packet.ReadByte(); switch (mode) { case TrophyHandlerMode.ClaimReward: HandleClaimReward(session, packet); break; case TrophyHandlerMode.Favorite: HandleFavorite(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { MasteryMode mode = (MasteryMode)packet.ReadByte(); switch (mode) { case MasteryMode.RewardBox: HandleRewardBox(session, packet); break; case MasteryMode.CraftItem: HandleCraftItem(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { ChangeAttributeMode mode = (ChangeAttributeMode)packet.ReadByte(); switch (mode) { case ChangeAttributeMode.ChangeAttributes: HandleChangeAttributes(session, packet); break; case ChangeAttributeMode.SelectNewAttributes: HandleSelectNewAttributes(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
private void Start() { // 反射注册包和包处理函数。 Type packetBaseType = typeof(ServerToClientPacketBase); Type packetHandlerBaseType = typeof(PacketHandlerBase); Assembly assembly = Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { if (!types[i].IsClass || types[i].IsAbstract) { continue; } if (types[i].BaseType == packetBaseType) { PacketBase packetBase = (PacketBase)Activator.CreateInstance(types[i]); Type packetType = GetServerToClientPacketType(packetBase.Id); if (packetType != null) { Log.Warning("Already exist packet type '{0}', check '{1}' or '{2}'?.", packetBase.Id.ToString(), packetType.Name, packetBase.GetType().Name); continue; } m_ServerToClientPacketTypes.Add(packetBase.Id, types[i]); } else if (types[i].BaseType == packetHandlerBaseType) { IPacketHandler packetHandler = (IPacketHandler)Activator.CreateInstance(types[i]); GameEntry.Network.RegisterHandler(packetHandler); } } GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkConnected, OnNetworkConnected); GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkClosed, OnNetworkClosed); GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkSendPacket, OnNetworkSendPacket); GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkMissHeartBeat, OnNetworkMissHeartBeat); GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkError, OnNetworkError); GameEntry.Event.Subscribe(UnityGameFramework.Runtime.EventId.NetworkCustomError, OnNetworkCustomError); }
public override void Handle(GameSession session, PacketReader packet) { short unk = packet.ReadShort(); NewsNotificationMode mode = (NewsNotificationMode)packet.ReadByte(); switch (mode) { case NewsNotificationMode.OpenBrowser: HandleOpenBrowser(session); break; case NewsNotificationMode.OpenSidebar: HandleOpenSidebar(session); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { GuildMode mode = (GuildMode)packet.ReadByte(); switch (mode) { case GuildMode.Create: HandleCreate(session, packet); break; case GuildMode.CheckIn: HandleCheckIn(session, packet); break; case GuildMode.EnterHouse: HandleEnterHouse(session, packet); break; case GuildMode.GuildWindow: HandleGuildWindowRequest(session, packet); break; case GuildMode.List: HandleList(session, packet); break; case GuildMode.GuildNotice: HandleGuildNotice(session, packet); break; case GuildMode.GuildDonate: HandleGuildDonate(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { DungeonMode mode = (DungeonMode)packet.ReadByte(); switch (mode) { case DungeonMode.EnterDungeonPortal: HandleEnterDungeonPortal(session); break; case DungeonMode.CreateDungeon: HandleCreateDungeon(session, packet); break; case DungeonMode.EnterDungeonButton: HandleEnterDungeonButton(session); break; case DungeonMode.AddRewards: HandleAddRewards(session, packet); break; case DungeonMode.GetHelp: HandleGetHelp(session, packet); break; case DungeonMode.Veteran: HandleVeteran(session, packet); break; case DungeonMode.Favorite: HandleFavorite(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { ClubMode mode = (ClubMode)packet.ReadByte(); switch (mode) { case ClubMode.Create: HandleCreate(session, packet); break; case ClubMode.Join: HandleJoin(session, packet); break; case ClubMode.SendInvite: HandleSendInvite(session, packet); break; case ClubMode.InviteResponse: HandleInviteResponse(session, packet); break; case ClubMode.Leave: HandleLeave(session, packet); break; case ClubMode.Buff: HandleBuff(packet); break; case ClubMode.Rename: HandleRename(packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { MailMode mode = (MailMode)packet.ReadByte(); switch (mode) { case MailMode.Open: HandleOpen(session); break; case MailMode.Send: HandleSend(session, packet); break; case MailMode.Read: HandleRead(session, packet); break; case MailMode.Collect: HandleCollect(session, packet); break; case MailMode.Delete: HandleDelete(session, packet); break; case MailMode.ReadBatch: HandleReadBatch(session, packet); break; case MailMode.CollectBatch: HandleCollectBatch(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { InstrumentMode mode = (InstrumentMode)packet.ReadByte(); switch (mode) { case InstrumentMode.StartImprovise: HandleStartImprovise(session, packet); break; case InstrumentMode.PlayNote: HandlePlayNote(session, packet); break; case InstrumentMode.StopImprovise: HandleStopImprovise(session); break; case InstrumentMode.PlayScore: HandlePlayScore(session, packet); break; case InstrumentMode.StopScore: HandleStopScore(session, packet); break; case InstrumentMode.Fireworks: HandleFireworks(session); break; case InstrumentMode.AudienceEmote: HandleAudienceEmote(session, packet); break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public override void Handle(GameSession session, PacketReader packet) { SkillHandlerMode mode = (SkillHandlerMode) packet.ReadByte(); switch (mode) { case SkillHandlerMode.FirstSent: HandleFirstSent(session, packet); break; case SkillHandlerMode.Damage: HandleDamage(session, packet); break; case SkillHandlerMode.Mode3: HandleMode3(packet); break; case SkillHandlerMode.Mode4: HandleMode4(packet); break; default: IPacketHandler<GameSession>.LogUnknownMode(mode); break; } }
/// <summary> /// Parses a packet and gets a response packet from the handler /// </summary> /// <param name="packetHandler"></param> /// <param name="sharedSecret"></param> /// <param name="packetBytes"></param> /// <param name="remoteEndpoint"></param> /// <returns></returns> internal IRadiusPacket GetResponsePacket(IPacketHandler packetHandler, String sharedSecret, Byte[] packetBytes, IPEndPoint remoteEndpoint) { var requestPacket = RadiusPacket.Parse(packetBytes, _dictionary, Encoding.UTF8.GetBytes(sharedSecret)); _log.Info($"Received {requestPacket.Code} from {remoteEndpoint} Id={requestPacket.Identifier}"); if (_log.IsDebugEnabled) { DumpPacket(requestPacket); } _log.Debug(packetBytes.ToHexString()); // Handle status server requests in server outside packet handler if (requestPacket.Code == PacketCode.StatusServer) { var responseCode = _serverType == RadiusServerType.Authentication ? PacketCode.AccessAccept : PacketCode.AccountingResponse; _log.Debug($"Sending {responseCode} for StatusServer request from {remoteEndpoint}"); return(requestPacket.CreateResponsePacket(responseCode)); } _log.Debug($"Handling packet for remote ip {remoteEndpoint.Address} with {packetHandler.GetType()}"); var sw = Stopwatch.StartNew(); var responsePacket = packetHandler.HandlePacket(requestPacket); sw.Stop(); _log.Debug($"{remoteEndpoint} Id={responsePacket.Identifier}, Received {responsePacket.Code} from handler in {sw.ElapsedMilliseconds}ms"); if (sw.ElapsedMilliseconds >= 5000) { _log.Warn($"Slow response for Id {responsePacket.Identifier}, check logs"); } if (requestPacket.Attributes.ContainsKey("Proxy-State")) { responsePacket.Attributes.Add("Proxy-State", requestPacket.Attributes.SingleOrDefault(o => o.Key == "Proxy-State").Value); } return(responsePacket); }
private void HandlePacket(Client client, Packet packet) { Logger.LogUnknownIncomingPacket(client, packet); if (!_packetHandlerLookup.ContainsKey(packet.Id)) { //Logger.LogUnknownIncomingPacket(client, packet); return; } IPacketHandler packetHandler = _packetHandlerLookup[packet.Id]; //Logger.LogIncomingPacket(client, packet); packet.Data.SetPositionStart(); try { packetHandler.Handle(client, packet); } catch (Exception ex) { Logger.Exception(client, ex); } }
public ScalingPacketQueueHandler(ILogger logger, IPacketHandler <T> packetHandler, QueueHandlerScalingConfig?config = null, int sleepTime = 10) { this.logger = logger; this.packetHandler = packetHandler; this.config = config ?? new(); this.sleepTime = sleepTime; this.workers = new(); for (int i = 0; i < this.config.MinWorkerCount; i++) { AddWorker(); } this.timer = new Timer(this.config.NewWorkerTimeout) { AutoReset = true, }; this.timer.Start(); this.timer.Elapsed += (sender, args) => CheckWorkerCount(); this.pulseTaskCompletionSource = new(); }
/// <summary> /// Loads packet handlers to be used for handling incoming data from this game client. /// </summary> /// <param name="client"></param> public virtual void LoadPacketHandlers(string version, out IPacketHandler[] packetHandlers, out List<PacketHandlerAttribute> attributes) { packetHandlers = new IPacketHandler[256]; attributes = new List<PacketHandlerAttribute>(); Array.Clear(packetHandlers, 0, packetHandlers.Length); lock (m_packetHandlerCacheLock) { if (!m_cachedPacketHandlerSearchResults.ContainsKey(version)) { int count = SearchAndAddPacketHandlers(version, Assembly.GetAssembly(typeof(GameServer)), packetHandlers); if (log.IsInfoEnabled) log.Info("PacketProcessor: Loaded " + count + " handlers from GameServer Assembly!"); count = 0; foreach (Assembly asm in ScriptMgr.Scripts) { count += SearchAndAddPacketHandlers(version, asm, packetHandlers); } if (log.IsInfoEnabled) log.Info("PacketProcessor: Loaded " + count + " handlers from Script Assemblys!"); //save search result for next login m_cachedPacketHandlerSearchResults.Add(version, (IPacketHandler[])packetHandlers.Clone()); } else { packetHandlers = (IPacketHandler[])m_cachedPacketHandlerSearchResults[version].Clone(); int count = 0; foreach (IPacketHandler ph in packetHandlers) if (ph != null) count++; log.Info("PacketProcessor: Loaded " + count + " handlers from cache for version="+version+"!"); } if (m_cachedPreprocessorSearchResults.ContainsKey(version)) attributes = m_cachedPreprocessorSearchResults[version]; log.Info("PacketProcessor: Loaded " + attributes.Count + " preprocessors from cache for version=" + version + "!"); } }
public override void Handle(GameSession session, PacketReader packet) { BonusGameType mode = (BonusGameType)packet.ReadByte(); switch (mode) { case BonusGameType.Open: HandleOpen(session, packet); break; case BonusGameType.Spin: HandleSpin(session); break; case BonusGameType.Close: break; default: IPacketHandler <GameSession> .LogUnknownMode(mode); break; } }
public void HandlePacket(GSPacketIn packet) { if (packet == null || m_client == null) return; int code = packet.ID; Statistics.BytesIn += packet.PacketSize; Statistics.PacketsIn++; SavePacket(packet); IPacketHandler packetHandler = null; if (code < m_packetHandlers.Length) { packetHandler = m_packetHandlers[code]; } else if (log.IsErrorEnabled) { log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + m_client); log.Error(Marshal.ToHexDump( String.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", code, code ^ 168, (m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint, packet.PacketSize, Thread.CurrentThread.ManagedThreadId), packet.ToArray())); } // make sure we can handle this packet at this stage var preprocess = PacketPreprocessing.CanProcessPacket(m_client, packet); if(!preprocess) { // this packet can't be processed by this client right now, for whatever reason return; } if (packetHandler != null) { Timer monitorTimer = null; if (log.IsDebugEnabled) { try { monitorTimer = new Timer(10000); m_activePacketHandler = packetHandler; m_handlerThreadID = Thread.CurrentThread.ManagedThreadId; monitorTimer.Elapsed += HandlePacketTimeout; monitorTimer.Start(); } catch (Exception e) { if (log.IsErrorEnabled) log.Error("Starting packet monitor timer", e); if (monitorTimer != null) { monitorTimer.Stop(); monitorTimer.Close(); monitorTimer = null; } } } #if LOGACTIVESTACKS //Put the current thread into the active thread list! //No need to lock the hashtable since we created it //synchronized! One reader, multiple writers supported! m_activePacketThreads.Add(Thread.CurrentThread, m_client); #endif long start = Environment.TickCount; try { packetHandler.HandlePacket(m_client, packet); } catch (Exception e) { if (log.IsErrorEnabled) { string client = (m_client == null ? "null" : m_client.ToString()); log.Error( "Error while processing packet (handler=" + packetHandler.GetType().FullName + " client: " + client + ")", e); } } #if LOGACTIVESTACKS finally { //Remove the thread from the active list after execution //No need to lock the hashtable since we created it //synchronized! One reader, multiple writers supported! m_activePacketThreads.Remove(Thread.CurrentThread); } #endif long timeUsed = Environment.TickCount - start; if (monitorTimer != null) { monitorTimer.Stop(); monitorTimer.Close(); } m_activePacketHandler = null; if (timeUsed > 1000) { string source = ((m_client.Account != null) ? m_client.Account.Name : m_client.TcpEndpoint); if (log.IsWarnEnabled) log.Warn("(" + source + ") Handle packet Thread " + Thread.CurrentThread.ManagedThreadId + " " + packetHandler + " took " + timeUsed + "ms!"); } } }
/// <summary> /// Registers a packet handler /// </summary> /// <param name="handler">The packet handler to register</param> /// <param name="packetCode">The packet ID to register it with</param> public static void RegisterPacketHandler(int packetCode, IPacketHandler handler) { if (m_packetHandlers[packetCode] != null) { log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1}", packetCode, handler.GetType().FullName); } m_packetHandlers[packetCode] = handler; }
public void HandlePacket(GSPacketIn packet) { int code = packet.Code; Statistics.BytesIn += packet.Length; Statistics.PacketsIn++; IPacketHandler packetHandler = null; if (code < m_packetHandlers.Length) packetHandler = m_packetHandlers[code]; else if (log.IsErrorEnabled) { log.ErrorFormat("Received packet code is outside of m_packetHandlers array bounds! " + m_client.ToString()); log.Error(Marshal.ToHexDump( String.Format("===> <{2}> Packet 0x{0:X2} (0x{1:X2}) length: {3} (ThreadId={4})", code, code ^ 168, m_client.TcpEndpoint, packet.Length, Thread.CurrentThread.ManagedThreadId), packet.Buffer)); } if (packetHandler != null) { long start = Environment.TickCount; try { packetHandler.HandlePacket(m_client, packet); } catch (Exception e) { if (log.IsErrorEnabled) { string client = m_client.TcpEndpoint; log.Error("Error while processing packet (handler=" + packetHandler.GetType().FullName + " client: " + client + ")", e); log.Error(Marshal.ToHexDump("Package Buffer:", packet.Buffer, 0, packet.Length)); } } long timeUsed = Environment.TickCount - start; m_activePacketHandler = null; if (log.IsDebugEnabled) { log.Debug("Package process Time:" + timeUsed + "ms!"); } if (timeUsed > 1000) { string source = m_client.TcpEndpoint; if (log.IsWarnEnabled) log.Warn("(" + source + ") Handle packet Thread " + Thread.CurrentThread.ManagedThreadId + " " + packetHandler + " took " + timeUsed + "ms!"); } } }
/// <summary> /// Registers a packet handler /// </summary> /// <param name="handler">The packet handler to register</param> /// <param name="packetCode">The packet ID to register it with</param> public static void RegisterPacketHandler(int packetCode, IPacketHandler handler) { m_packetHandlers[packetCode] = handler; }
private static void RegisterPacketHandler(int code, IPacketHandler iPackageHandler) { m_packagesHandlers[code] = iPackageHandler; }
/// <summary> /// Loads packet handlers to be used for handling incoming data from this game client. /// </summary> /// <param name="client"></param> public virtual void LoadPacketHandlers(string version, out IPacketHandler[] packetHandlers, out List<PacketHandlerAttribute> attributes) { packetHandlers = new IPacketHandler[256]; attributes = new List<PacketHandlerAttribute>(); Array.Clear(packetHandlers, 0, packetHandlers.Length); lock (m_packetHandlerCacheLock) { if (!m_cachedPacketHandlerSearchResults.ContainsKey(version)) { int count = SearchAndAddPacketHandlers(version, Assembly.GetAssembly(typeof(GameServer)), packetHandlers); if (log.IsInfoEnabled) log.Info("PacketProcessor: Loaded " + count + " handlers from GameServer Assembly!"); count = 0; foreach (Assembly asm in ScriptMgr.Scripts) { count += SearchAndAddPacketHandlers(version, asm, packetHandlers); } if (log.IsInfoEnabled) log.Info("PacketProcessor: Loaded " + count + " handlers from Script Assemblys!"); //save search result for next login m_cachedPacketHandlerSearchResults.Add(version, (IPacketHandler[])packetHandlers.Clone()); } else { packetHandlers = (IPacketHandler[])m_cachedPacketHandlerSearchResults[version].Clone(); int count = 0; foreach (IPacketHandler ph in packetHandlers) if (ph != null) count++; log.Info("PacketProcessor: Loaded " + count + " handlers from cache for version="+version+"!"); } if (m_cachedPreprocessorSearchResults.ContainsKey(version)) attributes = m_cachedPreprocessorSearchResults[version]; log.Info("PacketProcessor: Loaded " + attributes.Count + " preprocessors from cache for version=" + version + "!"); } }
public static void Add(RecvOps opcode, IPacketHandler handler) { m_handlers[(short)opcode] = handler; }
/// <summary> /// Registers a packet handler /// </summary> /// <param name="handler">The packet handler to register</param> /// <param name="packetCode">The packet ID to register it with</param> public void RegisterPacketHandler(int packetCode, IPacketHandler handler, IPacketHandler[] packetHandlers) { if (packetHandlers[packetCode] != null) { log.InfoFormat("Overwriting Client Packet Code {0}, with handler {1} in PacketProcessor", packetCode, handler.GetType().FullName); } packetHandlers[packetCode] = handler; }
/// <summary> /// Searches an assembly for packet handlers /// </summary> /// <param name="version">namespace of packethandlers to search eg. 'v167'</param> /// <param name="assembly">Assembly to search</param> /// <returns>The number of handlers loaded</returns> protected int SearchAndAddPacketHandlers(string version, Assembly assembly, IPacketHandler[] packetHandlers) { int count = 0; // Walk through each type in the assembly foreach (Type type in assembly.GetTypes()) { // Pick up a class if (type.IsClass != true) continue; if (type.GetInterface("DOL.GS.PacketHandler.IPacketHandler") == null) continue; if (!type.Namespace.ToLower().EndsWith(version.ToLower())) continue; var packethandlerattribs = (PacketHandlerAttribute[]) type.GetCustomAttributes(typeof (PacketHandlerAttribute), true); if (packethandlerattribs.Length > 0) { count++; RegisterPacketHandler(packethandlerattribs[0].Code, (IPacketHandler) Activator.CreateInstance(type), packetHandlers); if (!m_cachedPreprocessorSearchResults.ContainsKey(version)) m_cachedPreprocessorSearchResults.Add(version, new List<PacketHandlerAttribute>()); m_cachedPreprocessorSearchResults[version].Add(packethandlerattribs[0]); } } return count; }