46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
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;
|
|
private readonly IDictionary<short, IMessageEvent> _messageEvents;
|
|
private readonly IDictionary<short, string> _messageNames;
|
|
|
|
public MessageHandler(ILogger<MessageHandler> logger, IEnumerable<IMessageEvent> messageEvents)
|
|
{
|
|
_logger = logger;
|
|
_messageEvents = messageEvents.ToDictionary(messageEvent => (short)messageEvent.Header);
|
|
|
|
_messageNames = new Dictionary<short, string>();
|
|
|
|
foreach (var name in Enum.GetNames(typeof(IncomingHeaders)))
|
|
{
|
|
_messageNames.Add((short)Enum.Parse(typeof(IncomingHeaders), name), name);
|
|
}
|
|
}
|
|
|
|
public async Task TryHandleAsync(GameSession session, ClientMessage request)
|
|
{
|
|
if (request.Header == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (_messageEvents.TryGetValue(request.Header.Value, out var messageEvent))
|
|
{
|
|
_logger.LogInformation("Handling header ID {Header} on class {Class}", request.Header.Value, messageEvent.GetType());
|
|
|
|
await messageEvent.HandleAsync(session, request);
|
|
}
|
|
else
|
|
{
|
|
_logger.LogWarning("Unregistered header {Header} {Name}", request.Header.Value, _messageNames.TryGetValue(request.Header.Value, out var messageName) ? messageName : string.Empty);
|
|
}
|
|
}
|
|
} |