NetworkMessageRegistry.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Microsoft.Xna.Framework.Net
  4. {
  5. /// <summary>
  6. /// Provides a registry for network message types, allowing messages to be registered and created dynamically.
  7. /// </summary>
  8. public static class NetworkMessageRegistry
  9. {
  10. private static readonly Dictionary<byte, Func<INetworkMessage>> registry = new();
  11. /// <summary>
  12. /// Registers a network message type with the specified type identifier.
  13. /// </summary>
  14. /// <typeparam name="T">The type of the network message to register. Must implement <see cref="INetworkMessage"/> and have a parameterless constructor.</typeparam>
  15. /// <param name="typeId">The unique identifier for the message type.</param>
  16. public static void Register<T>(byte typeId) where T : INetworkMessage, new()
  17. {
  18. registry[typeId] = () => new T();
  19. }
  20. /// <summary>
  21. /// Creates a network message instance based on the specified type identifier.
  22. /// </summary>
  23. /// <param name="typeId">The unique identifier for the message type.</param>
  24. /// <returns>An instance of the network message, or <c>null</c> if the type identifier is not registered.</returns>
  25. public static INetworkMessage CreateMessage(byte typeId)
  26. {
  27. return registry.TryGetValue(typeId, out var ctor) ? ctor() : null;
  28. }
  29. static NetworkMessageRegistry()
  30. {
  31. Register<JoinRequestMessage>(2);
  32. Register<JoinAcceptedMessage>(3);
  33. Register<ReadinessUpdateMessage>(4);
  34. Register<GameStateChangeMessage>(5);
  35. Register<JoinRejectedMessage>(6);
  36. Register<HeartbeatMessage>(7);
  37. Register<HeartbeatReplyMessage>(8);
  38. Register<GamerLeavingMessage>(9); // Phase 2: Graceful leave protocol
  39. Register<SessionStateMessage>(10); // Phase 2: Session state synchronization
  40. }
  41. }
  42. }