TigerEmu/Communication/Messages/MessageHandler.cs

41 lines
1.5 KiB
C#
Raw Normal View History

2023-09-23 11:11:07 +00:00
using Microsoft.Extensions.Logging;
using Tiger.Communication.Messages.Incoming;
using Tiger.Communication.Messages.Interfaces;
using Tiger.Communication.Messages.Types;
using Tiger.Networking.Game.Sessions;
namespace Tiger.Communication.Messages;
public class MessageHandler : IMessageHandler
{
private readonly ILogger<MessageHandler> _logger;
2023-11-10 13:55:42 +00:00
private readonly IDictionary<int, IMessageEvent> _messageEvents;
private readonly IDictionary<int, string> _messageNames;
2023-09-23 11:11:07 +00:00
public MessageHandler(ILogger<MessageHandler> logger, IEnumerable<IMessageEvent> messageEvents)
{
_logger = logger;
2023-11-10 13:55:42 +00:00
_messageEvents = messageEvents.ToDictionary(messageEvent => (int)messageEvent.Header);
2023-09-23 11:11:07 +00:00
2023-11-10 13:55:42 +00:00
_messageNames = new Dictionary<int, string>();
2023-09-23 11:11:07 +00:00
foreach (var name in Enum.GetNames(typeof(IncomingHeaders)))
{
2023-11-10 13:55:42 +00:00
_messageNames.Add((int)Enum.Parse(typeof(IncomingHeaders), name), name);
2023-09-23 11:11:07 +00:00
}
}
public async Task TryHandleAsync(GameSession session, ClientMessage request)
{
if (_messageEvents.TryGetValue(request.Header, out var messageEvent))
2023-09-23 11:11:07 +00:00
{
_logger.LogInformation("Handling header ID {Header} on class {Class}", request.Header, messageEvent.GetType());
2023-09-23 11:11:07 +00:00
await messageEvent.HandleAsync(session, request);
}
else
{
_logger.LogWarning("Unregistered header {Header} {Name}", request.Header, _messageNames.TryGetValue(request.Header, out var messageName) ? messageName : string.Empty);
2023-09-23 11:11:07 +00:00
}
}
}