UdpNetworkSessionFactory.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. namespace Microsoft.Xna.Framework.Net
  6. {
  7. /// <summary>
  8. /// Default factory that creates UDP-based network sessions.
  9. /// This is the v1.0 implementation. Steam support can be added in v1.5.
  10. /// </summary>
  11. public class UdpNetworkSessionFactory : INetworkSessionFactory
  12. {
  13. /// <summary>
  14. /// Gets the name of this networking backend.
  15. /// </summary>
  16. public string BackendName => "UDP/SystemLink";
  17. /// <summary>
  18. /// Creates a new UDP-based network session.
  19. /// </summary>
  20. /// <returns>A new INetworkSession instance configured for UDP.</returns>
  21. public INetworkSession CreateSession()
  22. {
  23. return new UdpNetworkSession();
  24. }
  25. /// <summary>
  26. /// Finds available UDP sessions on the local network.
  27. /// </summary>
  28. public async Task<IEnumerable<SessionInfo>> FindSessionsAsync(NetworkSessionType sessionType)
  29. {
  30. var sessions = new List<SessionInfo>();
  31. // Query available sessions from NetworkSession
  32. try
  33. {
  34. var availableSessions = await NetworkSession.FindAsync(
  35. sessionType,
  36. maxLocalGamers: 1,
  37. sessionProperties: null
  38. );
  39. // Convert AvailableNetworkSession to SessionInfo
  40. foreach (var session in availableSessions)
  41. {
  42. sessions.Add(new SessionInfo
  43. {
  44. SessionId = session.SessionId,
  45. JoinAddress = session.HostEndpoint?.ToString() ?? "",
  46. HostName = session.HostGamertag,
  47. CurrentPlayerCount = session.CurrentGamerCount,
  48. MaxPlayerCount = session.OpenPublicGamerSlots + session.OpenPrivateGamerSlots,
  49. IsPasswordProtected = false,
  50. SessionType = sessionType
  51. });
  52. }
  53. }
  54. catch (Exception ex)
  55. {
  56. System.Diagnostics.Debug.WriteLine($"Error finding sessions: {ex}");
  57. }
  58. return sessions;
  59. }
  60. }
  61. }