NetworkServiceProvider.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. namespace Microsoft.Xna.Framework.Net
  3. {
  4. /// <summary>
  5. /// Service locator for network session factories.
  6. /// Manages the global network session factory instance for the application.
  7. /// This enables switching between different networking backends (UDP, Steam, etc.) at runtime.
  8. /// </summary>
  9. public static class NetworkServiceProvider
  10. {
  11. private static INetworkSessionFactory sessionFactory;
  12. private static readonly object lockObject = new object();
  13. /// <summary>
  14. /// Gets the current network session factory.
  15. /// </summary>
  16. /// <exception cref="InvalidOperationException">Thrown if no factory has been configured.</exception>
  17. public static INetworkSessionFactory SessionFactory
  18. {
  19. get
  20. {
  21. lock (lockObject)
  22. {
  23. if (sessionFactory == null)
  24. {
  25. throw new InvalidOperationException(
  26. "Network session factory not configured. " +
  27. "Call NetworkServiceProvider.SetSessionFactory() during game initialization.");
  28. }
  29. return sessionFactory;
  30. }
  31. }
  32. }
  33. /// <summary>
  34. /// Sets the network session factory.
  35. /// This should be called once during game initialization.
  36. /// </summary>
  37. /// <param name="factory">The network session factory to use.</param>
  38. /// <exception cref="ArgumentNullException">Thrown if factory is null.</exception>
  39. public static void SetSessionFactory(INetworkSessionFactory factory)
  40. {
  41. if (factory == null)
  42. throw new ArgumentNullException(nameof(factory));
  43. lock (lockObject)
  44. {
  45. sessionFactory = factory;
  46. System.Diagnostics.Debug.WriteLine($"[Network] Using {factory.BackendName} backend");
  47. }
  48. }
  49. /// <summary>
  50. /// Resets the session factory to default (UDP-based).
  51. /// </summary>
  52. public static void ResetToDefault()
  53. {
  54. lock (lockObject)
  55. {
  56. sessionFactory = new UdpNetworkSessionFactory();
  57. System.Diagnostics.Debug.WriteLine("[Network] Reset to default UDP backend");
  58. }
  59. }
  60. /// <summary>
  61. /// Gets a value indicating whether a session factory has been configured.
  62. /// </summary>
  63. public static bool IsConfigured
  64. {
  65. get
  66. {
  67. lock (lockObject)
  68. {
  69. return sessionFactory != null;
  70. }
  71. }
  72. }
  73. }
  74. }