NetworkSession.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. using System;
  2. using System.Net;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Microsoft.Xna.Framework.GamerServices;
  10. namespace Microsoft.Xna.Framework.Net
  11. {
  12. /// <summary>
  13. /// Represents a network session for multiplayer gaming.
  14. /// </summary>
  15. public class NetworkSession : IDisposable, IAsyncDisposable
  16. {
  17. // Event for received messages
  18. public event EventHandler<MessageReceivedEventArgs> MessageReceived;
  19. private readonly List<NetworkGamer> gamers;
  20. private readonly GamerCollection gamerCollection;
  21. private readonly NetworkSessionType sessionType;
  22. private readonly int maxGamers;
  23. private readonly int privateGamerSlots;
  24. private readonly Dictionary<string, IPEndPoint> gamerEndpoints;
  25. private readonly object lockObject = new object();
  26. private INetworkTransport networkTransport;
  27. internal NetworkSessionState sessionState;
  28. private bool disposed;
  29. private bool isHost;
  30. internal string sessionId;
  31. private Task receiveTask;
  32. private CancellationTokenSource cancellationTokenSource;
  33. // Events
  34. public event EventHandler<GameStartedEventArgs> GameStarted;
  35. public event EventHandler<GameEndedEventArgs> GameEnded;
  36. private event EventHandler<GamerJoinedEventArgs> gamerJoined;
  37. private bool isGamerJoinedSubscribed = false;
  38. public event EventHandler<GamerJoinedEventArgs> GamerJoined
  39. {
  40. add
  41. {
  42. lock (lockObject)
  43. {
  44. gamerJoined += value;
  45. isGamerJoinedSubscribed = true;
  46. // Notify pending gamers if this is the first subscription
  47. NotifyPendingGamers();
  48. }
  49. }
  50. remove
  51. {
  52. lock (lockObject)
  53. {
  54. gamerJoined -= value;
  55. isGamerJoinedSubscribed = gamerJoined != null;
  56. }
  57. }
  58. }
  59. public event EventHandler<GamerLeftEventArgs> GamerLeft;
  60. public event EventHandler<NetworkSessionEndedEventArgs> SessionEnded;
  61. // Static event for invite acceptance
  62. public static event EventHandler<InviteAcceptedEventArgs> InviteAccepted;
  63. /// <summary>
  64. /// Allows changing the network transport implementation.
  65. /// </summary>
  66. public INetworkTransport NetworkTransport
  67. {
  68. get => networkTransport;
  69. set => networkTransport = value ?? throw new ArgumentNullException(nameof(value));
  70. }
  71. /// <summary>
  72. /// Initializes a new NetworkSession.
  73. /// </summary>
  74. private NetworkSession(NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, bool isHost)
  75. {
  76. // Register message types (can be moved to static constructor)
  77. NetworkMessageRegistry.Register<PlayerMoveMessage>(1);
  78. this.sessionType = sessionType;
  79. this.maxGamers = maxGamers;
  80. this.privateGamerSlots = privateGamerSlots;
  81. this.isHost = isHost;
  82. this.sessionId = Guid.NewGuid().ToString();
  83. this.sessionState = NetworkSessionState.Creating;
  84. gamers = new List<NetworkGamer>();
  85. gamerCollection = new GamerCollection(gamers);
  86. gamerEndpoints = new Dictionary<string, IPEndPoint>();
  87. networkTransport = new UdpTransport();
  88. cancellationTokenSource = new CancellationTokenSource();
  89. // Add local gamer
  90. var gamerGuid = Guid.NewGuid().ToString();
  91. var localGamer = new LocalNetworkGamer(this, gamerGuid, isHost, $"{SignedInGamer.Current?.Gamertag ?? "Player"}_{gamerGuid.Substring(0, 8)}");
  92. NetworkGamer.LocalGamer = localGamer;
  93. AddGamer(localGamer);
  94. // Start receive loop for SystemLink sessions
  95. if (sessionType == NetworkSessionType.SystemLink)
  96. {
  97. receiveTask = Task.Run(() => ReceiveLoopAsync(cancellationTokenSource.Token));
  98. }
  99. }
  100. // Internal constructor for SystemLink join
  101. internal NetworkSession(NetworkSessionType sessionType, int maxGamers, int privateGamerSlots, bool isHost, string sessionId)
  102. : this(sessionType, maxGamers, privateGamerSlots, isHost)
  103. {
  104. this.sessionId = sessionId;
  105. this.sessionState = NetworkSessionState.Lobby;
  106. }
  107. /// <summary>
  108. /// Gets all gamers in the session.
  109. /// </summary>
  110. public GamerCollection AllGamers => gamerCollection;
  111. /// <summary>
  112. /// Gets local gamers in the session.
  113. /// </summary>
  114. public LocalGamerCollection LocalGamers
  115. {
  116. get
  117. {
  118. var localGamers = gamers.Where(g => g.IsLocal).OfType<LocalNetworkGamer>().ToList();
  119. return new LocalGamerCollection(localGamers);
  120. }
  121. }
  122. /// <summary>
  123. /// Gets remote gamers in the session.
  124. /// </summary>
  125. public GamerCollection RemoteGamers
  126. {
  127. get
  128. {
  129. var remoteGamers = gamers.Where(g => !g.IsLocal).ToList();
  130. return new GamerCollection(remoteGamers);
  131. }
  132. }
  133. /// <summary>
  134. /// Gets the host gamer.
  135. /// </summary>
  136. public NetworkGamer Host => AllGamers.Host;
  137. /// <summary>
  138. /// Gets whether this machine is the host.
  139. /// </summary>
  140. public bool IsHost => isHost;
  141. /// <summary>
  142. /// Gets whether everyone is ready to start the game.
  143. /// </summary>
  144. public bool IsEveryoneReady => AllGamers.All(g => g.IsReady);
  145. /// <summary>
  146. /// Gets the maximum number of gamers.
  147. /// </summary>
  148. public int MaxGamers => maxGamers;
  149. /// <summary>
  150. /// Gets the number of private gamer slots.
  151. /// </summary>
  152. public int PrivateGamerSlots => privateGamerSlots;
  153. /// <summary>
  154. /// Gets the session type.
  155. /// </summary>
  156. public NetworkSessionType SessionType => sessionType;
  157. /// <summary>
  158. /// Gets the current session state.
  159. /// </summary>
  160. public NetworkSessionState SessionState => sessionState;
  161. /// <summary>
  162. /// Gets the bytes per second being sent.
  163. /// </summary>
  164. public int BytesPerSecondSent => 0; // Mock implementation
  165. /// <summary>
  166. /// Gets the bytes per second being received.
  167. /// </summary>
  168. public int BytesPerSecondReceived => 0; // Mock implementation
  169. /// <summary>
  170. /// Gets whether the session allows host migration.
  171. /// </summary>
  172. public bool AllowHostMigration { get; set; } = true;
  173. /// <summary>
  174. /// Gets whether the session allows gamers to join during gameplay.
  175. /// </summary>
  176. public bool AllowJoinInProgress { get; set; } = true;
  177. private IDictionary<string, object> sessionProperties = new Dictionary<string, object>();
  178. /// <summary>
  179. /// Gets or sets custom session properties.
  180. /// </summary>
  181. public IDictionary<string, object> SessionProperties
  182. {
  183. get => sessionProperties;
  184. set
  185. {
  186. sessionProperties = value ?? throw new ArgumentNullException(nameof(value));
  187. // Automatically broadcast changes if this machine is the host
  188. if (IsHost)
  189. {
  190. BroadcastSessionProperties();
  191. }
  192. }
  193. }
  194. // Simulation properties for testing network conditions
  195. private TimeSpan simulatedLatency = TimeSpan.Zero;
  196. private float simulatedPacketLoss = 0.0f;
  197. /// <summary>
  198. /// Gets or sets the simulated network latency for testing purposes.
  199. /// </summary>
  200. public TimeSpan SimulatedLatency
  201. {
  202. get => simulatedLatency;
  203. set => simulatedLatency = value;
  204. }
  205. /// <summary>
  206. /// Gets or sets the simulated packet loss percentage for testing purposes.
  207. /// </summary>
  208. public float SimulatedPacketLoss
  209. {
  210. get => simulatedPacketLoss;
  211. set => simulatedPacketLoss = Math.Max(0.0f, Math.Min(1.0f, value));
  212. }
  213. /// <summary>
  214. /// Cancels all ongoing async operations for this session.
  215. /// </summary>
  216. public void Cancel()
  217. {
  218. cancellationTokenSource?.Cancel();
  219. }
  220. /// <summary>
  221. /// Asynchronously creates a new network session.
  222. /// </summary>
  223. public static async Task<NetworkSession> CreateAsync(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, IDictionary<string, object> sessionProperties, CancellationToken cancellationToken = default)
  224. {
  225. if (maxLocalGamers < 1 || maxLocalGamers > 4)
  226. throw new ArgumentOutOfRangeException(nameof(maxLocalGamers));
  227. if (privateGamerSlots < 0 || privateGamerSlots > maxGamers)
  228. throw new ArgumentOutOfRangeException(nameof(privateGamerSlots));
  229. NetworkSession session = null;
  230. switch (sessionType)
  231. {
  232. case NetworkSessionType.Local:
  233. // Local session: in-memory only
  234. await Task.Delay(5, cancellationToken);
  235. session = new NetworkSession(sessionType, maxGamers, privateGamerSlots, true);
  236. session.sessionState = NetworkSessionState.Lobby;
  237. // Register in local session list for FindAsync
  238. LocalSessionRegistry.RegisterSession(session);
  239. break;
  240. case NetworkSessionType.SystemLink:
  241. // SystemLink: start UDP listener and broadcast session
  242. session = new NetworkSession(sessionType, maxGamers, privateGamerSlots, true);
  243. session.sessionState = NetworkSessionState.Lobby;
  244. _ = SystemLinkSessionManager.AdvertiseSessionAsync(session, cancellationToken); // Fire-and-forget
  245. break;
  246. default:
  247. // Not implemented
  248. throw new NotSupportedException($"SessionType {sessionType} not supported yet.");
  249. }
  250. return session;
  251. }
  252. /// <summary>
  253. /// Synchronous wrapper for CreateAsync (for XNA compatibility).
  254. /// </summary>
  255. public static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers, int privateGamerSlots, IDictionary<string, object> sessionProperties)
  256. {
  257. return CreateAsync(sessionType, maxLocalGamers, maxGamers, privateGamerSlots, sessionProperties).GetAwaiter().GetResult();
  258. }
  259. /// <summary>
  260. /// Asynchronously finds available network sessions.
  261. /// </summary>
  262. public static async Task<AvailableNetworkSessionCollection> FindAsync(NetworkSessionType sessionType, int maxLocalGamers, IDictionary<string, object> sessionProperties, CancellationToken cancellationToken = default)
  263. {
  264. switch (sessionType)
  265. {
  266. case NetworkSessionType.Local:
  267. await Task.Delay(5, cancellationToken);
  268. // Return sessions in local registry
  269. var localSessions = LocalSessionRegistry.FindSessions(maxLocalGamers).ToList();
  270. return new AvailableNetworkSessionCollection(localSessions);
  271. case NetworkSessionType.SystemLink:
  272. // Discover sessions via UDP broadcast
  273. var systemLinkSessions = (await SystemLinkSessionManager.DiscoverSessionsAsync(maxLocalGamers, cancellationToken)).ToList();
  274. return new AvailableNetworkSessionCollection(systemLinkSessions);
  275. default:
  276. throw new NotSupportedException($"SessionType {sessionType} not supported yet.");
  277. }
  278. }
  279. /// <summary>
  280. /// Synchronous wrapper for FindAsync (for XNA compatibility).
  281. /// </summary>
  282. public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int maxLocalGamers, IDictionary<string, object> sessionProperties)
  283. {
  284. return FindAsync(sessionType, maxLocalGamers, sessionProperties).GetAwaiter().GetResult();
  285. }
  286. /// <summary>
  287. /// Asynchronously joins an available network session.
  288. /// </summary>
  289. public static async Task<NetworkSession> JoinAsync(AvailableNetworkSession availableSession, CancellationToken cancellationToken = default)
  290. {
  291. switch (availableSession.SessionType)
  292. {
  293. case NetworkSessionType.Local:
  294. // Attach to local session
  295. var localSession = LocalSessionRegistry.GetSessionById(availableSession.SessionId);
  296. if (localSession == null)
  297. throw new NetworkSessionJoinException(NetworkSessionJoinError.SessionNotFound);
  298. // Add local gamer
  299. var newGamer = new LocalNetworkGamer(localSession, Guid.NewGuid().ToString(), false, SignedInGamer.Current?.Gamertag ?? "Player");
  300. localSession.AddGamer(newGamer);
  301. return localSession;
  302. case NetworkSessionType.SystemLink:
  303. // Connect to host via network
  304. var joinedSession = await SystemLinkSessionManager.JoinSessionAsync(availableSession, cancellationToken);
  305. return joinedSession;
  306. default:
  307. throw new NotSupportedException($"SessionType {availableSession.SessionType} not supported yet.");
  308. }
  309. }
  310. public static Task<NetworkSession> JoinInvitedAsync(IEnumerable<SignedInGamer> localGamers, object state = null, CancellationToken cancellationToken = default)
  311. {
  312. if (localGamers == null || !localGamers.Any())
  313. throw new ArgumentException("At least one local gamer must be provided.", nameof(localGamers));
  314. // Simulate invite acceptance logic
  315. var inviteAcceptedEventArgs = new InviteAcceptedEventArgs(localGamers.First(), true);
  316. InviteAccepted?.Invoke(null, inviteAcceptedEventArgs);
  317. if (!inviteAcceptedEventArgs.IsSignedInGamer)
  318. throw new InvalidOperationException("The gamer is not signed in.");
  319. // Simulate finding the session associated with the invite
  320. var availableSession = new AvailableNetworkSession(
  321. sessionName: "InvitedSession",
  322. hostGamertag: "HostPlayer",
  323. currentGamerCount: 1,
  324. openPublicGamerSlots: 3,
  325. openPrivateGamerSlots: 1,
  326. sessionType: NetworkSessionType.PlayerMatch,
  327. sessionProperties: new Dictionary<string, object>(),
  328. sessionId: Guid.NewGuid().ToString()
  329. );
  330. // Join the session
  331. var joinedSession = SystemLinkSessionManager.JoinSessionAsync(availableSession, cancellationToken);
  332. return joinedSession;
  333. }
  334. /// <summary>
  335. /// Creates a new network session synchronously with default properties.
  336. /// </summary>
  337. public static NetworkSession Create(NetworkSessionType sessionType, int maxLocalGamers, int maxGamers)
  338. {
  339. return CreateAsync(sessionType, maxLocalGamers, maxGamers, 0, new Dictionary<string, object>()).GetAwaiter().GetResult();
  340. }
  341. /// <summary>
  342. /// <summary>
  343. /// Finds available network sessions synchronously with default properties.
  344. /// </summary>
  345. public static AvailableNetworkSessionCollection Find(NetworkSessionType sessionType, int maxLocalGamers)
  346. {
  347. return FindAsync(sessionType, maxLocalGamers, new Dictionary<string, object>()).GetAwaiter().GetResult();
  348. }
  349. /// <summary>
  350. /// <summary>
  351. /// Joins an available network session synchronously.
  352. /// </summary>
  353. public static NetworkSession Join(AvailableNetworkSession availableSession)
  354. {
  355. return JoinAsync(availableSession).GetAwaiter().GetResult();
  356. }
  357. public static NetworkSession JoinInvited(IEnumerable<SignedInGamer> localGamers, object state = null)
  358. {
  359. return JoinInvitedAsync(localGamers, state).GetAwaiter().GetResult();
  360. }
  361. /// <summary>
  362. /// Updates the network session.
  363. /// </summary>
  364. public void Update()
  365. {
  366. if (disposed)
  367. return;
  368. // Process any pending network messages
  369. ProcessIncomingMessages();
  370. }
  371. /// <summary>
  372. /// Sends data to all gamers in the session.
  373. /// </summary>
  374. public void SendToAll(PacketWriter writer, SendDataOptions options)
  375. {
  376. SendToAll(writer, options, NetworkGamer.LocalGamer);
  377. }
  378. /// <summary>
  379. /// Sends data to all gamers except the specified sender.
  380. /// </summary>
  381. public void SendToAll(PacketWriter writer, SendDataOptions options, NetworkGamer sender)
  382. {
  383. if (writer == null)
  384. throw new ArgumentNullException(nameof(writer));
  385. byte[] data = writer.GetData();
  386. lock (lockObject)
  387. {
  388. foreach (var gamer in gamers)
  389. {
  390. if (gamer != sender && !gamer.IsLocal)
  391. {
  392. SendDataToGamer(gamer, data, options);
  393. }
  394. }
  395. }
  396. }
  397. /// <summary>
  398. /// Starts the game.
  399. /// </summary>
  400. public void StartGame()
  401. {
  402. if (sessionState == NetworkSessionState.Lobby)
  403. {
  404. sessionState = NetworkSessionState.Playing;
  405. OnGameStarted();
  406. }
  407. }
  408. /// <summary>
  409. /// Ends the game and returns to lobby.
  410. /// </summary>
  411. public void EndGame()
  412. {
  413. if (sessionState == NetworkSessionState.Playing)
  414. {
  415. sessionState = NetworkSessionState.Lobby;
  416. OnGameEnded();
  417. }
  418. }
  419. /// <summary>
  420. /// Notifies when a gamer's readiness changes.
  421. /// </summary>
  422. internal void NotifyReadinessChanged(NetworkGamer gamer)
  423. {
  424. // Send readiness update to other players
  425. if (IsHost)
  426. {
  427. var writer = new PacketWriter();
  428. writer.Write("ReadinessUpdate");
  429. writer.Write(gamer.Id);
  430. writer.Write(gamer.IsReady);
  431. SendToAll(writer, SendDataOptions.Reliable, gamer);
  432. }
  433. }
  434. /// <summary>
  435. /// Sends data to a specific gamer.
  436. /// </summary>
  437. internal void SendDataToGamer(NetworkGamer gamer, PacketWriter writer, SendDataOptions options)
  438. {
  439. SendDataToGamer(gamer, writer.GetData(), options);
  440. }
  441. internal void SendDataToGamer(NetworkGamer gamer, byte[] data, SendDataOptions options)
  442. {
  443. if (gamerEndpoints.TryGetValue(gamer.Id, out IPEndPoint endpoint))
  444. {
  445. try
  446. {
  447. networkTransport.Send(data, endpoint);
  448. }
  449. catch (Exception ex)
  450. {
  451. Debug.WriteLine($"Failed to send data to {gamer.Gamertag}: {ex.Message}");
  452. }
  453. }
  454. }
  455. public void AddLocalGamer(SignedInGamer gamer)
  456. {
  457. throw new NotImplementedException();
  458. }
  459. private void AddGamer(NetworkGamer gamer)
  460. {
  461. lock (lockObject)
  462. {
  463. gamers.Add(gamer);
  464. }
  465. OnGamerJoined(gamer);
  466. }
  467. private void RemoveGamer(NetworkGamer gamer)
  468. {
  469. lock (lockObject)
  470. {
  471. gamers.Remove(gamer);
  472. gamerEndpoints.Remove(gamer.Id);
  473. }
  474. OnGamerLeft(gamer);
  475. }
  476. // Modern async receive loop for SystemLink
  477. private async Task ReceiveLoopAsync(CancellationToken cancellationToken)
  478. {
  479. while (!cancellationToken.IsCancellationRequested)
  480. {
  481. try
  482. {
  483. // Ensure the network transport is bound before receiving data
  484. if (!networkTransport.IsBound)
  485. {
  486. networkTransport.Bind();
  487. }
  488. var (data, senderEndpoint) = await networkTransport.ReceiveAsync();
  489. if (data.Length > 1)
  490. {
  491. NetworkGamer senderGamer = null;
  492. lock (lockObject)
  493. {
  494. senderGamer = gamers.FirstOrDefault(g => gamerEndpoints.TryGetValue(g.Id, out var ep) && ep.Equals(senderEndpoint));
  495. }
  496. if (senderGamer != null)
  497. {
  498. senderGamer.EnqueueIncomingPacket(data, senderGamer);
  499. }
  500. var typeId = data[0];
  501. var reader = new PacketReader(data); // Use only the byte array
  502. var message = NetworkMessageRegistry.CreateMessage(typeId);
  503. message?.Deserialize(reader);
  504. OnMessageReceived(new MessageReceivedEventArgs(message, senderEndpoint));
  505. }
  506. }
  507. catch (ObjectDisposedException) { break; }
  508. catch (Exception ex)
  509. {
  510. Debug.WriteLine($"ReceiveLoop error: {ex.Message}");
  511. }
  512. }
  513. }
  514. private void OnMessageReceived(MessageReceivedEventArgs e)
  515. {
  516. // Raise the MessageReceived event
  517. var handler = MessageReceived;
  518. if (handler != null)
  519. handler(this, e);
  520. }
  521. private void OnGameStarted()
  522. {
  523. GameStarted?.Invoke(this, new GameStartedEventArgs());
  524. }
  525. private void OnGameEnded()
  526. {
  527. GameEnded?.Invoke(this, new GameEndedEventArgs());
  528. }
  529. private void OnGamerJoined(NetworkGamer gamer)
  530. {
  531. gamerJoined?.Invoke(this, new GamerJoinedEventArgs(gamer));
  532. }
  533. private void OnGamerLeft(NetworkGamer gamer)
  534. {
  535. GamerLeft?.Invoke(this, new GamerLeftEventArgs(gamer));
  536. }
  537. private void OnSessionEnded(NetworkSessionEndReason reason)
  538. {
  539. sessionState = NetworkSessionState.Ended;
  540. SessionEnded?.Invoke(this, new NetworkSessionEndedEventArgs(reason));
  541. }
  542. /// <summary>
  543. /// Disposes the network session.
  544. /// </summary>
  545. public void Dispose()
  546. {
  547. if (!disposed)
  548. {
  549. cancellationTokenSource?.Cancel();
  550. receiveTask?.Wait(1000); // Wait up to 1 second
  551. networkTransport?.Dispose();
  552. cancellationTokenSource?.Dispose();
  553. OnSessionEnded(NetworkSessionEndReason.ClientSignedOut);
  554. disposed = true;
  555. }
  556. }
  557. public async ValueTask DisposeAsync()
  558. {
  559. if (!disposed)
  560. {
  561. cancellationTokenSource?.Cancel();
  562. if (receiveTask != null)
  563. await receiveTask;
  564. if (networkTransport is IAsyncDisposable asyncTransport)
  565. await asyncTransport.DisposeAsync();
  566. else
  567. networkTransport?.Dispose();
  568. cancellationTokenSource?.Dispose();
  569. OnSessionEnded(NetworkSessionEndReason.ClientSignedOut);
  570. disposed = true;
  571. }
  572. }
  573. internal byte[] SerializeSessionPropertiesBinary()
  574. {
  575. using (var ms = new MemoryStream())
  576. using (var writer = new BinaryWriter(ms))
  577. {
  578. writer.Write(SessionProperties.Count);
  579. foreach (var kvp in SessionProperties)
  580. {
  581. writer.Write(kvp.Key);
  582. // Write type info and value
  583. if (kvp.Value is int i)
  584. {
  585. writer.Write((byte)1); // type marker
  586. writer.Write(i);
  587. }
  588. else if (kvp.Value is bool b)
  589. {
  590. writer.Write((byte)2);
  591. writer.Write(b);
  592. }
  593. else if (kvp.Value is string s)
  594. {
  595. writer.Write((byte)3);
  596. writer.Write(s ?? "");
  597. }
  598. // Add more types as needed
  599. else
  600. {
  601. writer.Write((byte)255); // unknown type
  602. writer.Write(kvp.Value?.ToString() ?? "");
  603. }
  604. }
  605. return ms.ToArray();
  606. }
  607. }
  608. internal void DeserializeSessionPropertiesBinary(byte[] data)
  609. {
  610. using (var ms = new MemoryStream(data))
  611. using (var reader = new BinaryReader(ms))
  612. {
  613. SessionProperties.Clear();
  614. int count = reader.ReadInt32();
  615. for (int i = 0; i < count; i++)
  616. {
  617. string key = reader.ReadString();
  618. byte type = reader.ReadByte();
  619. object value = null;
  620. switch (type)
  621. {
  622. case 1: value = reader.ReadInt32(); break;
  623. case 2: value = reader.ReadBoolean(); break;
  624. case 3: value = reader.ReadString(); break;
  625. default: value = reader.ReadString(); break;
  626. }
  627. SessionProperties[key] = value;
  628. }
  629. }
  630. }
  631. private void BroadcastSessionProperties()
  632. {
  633. var writer = new PacketWriter();
  634. writer.Write("SessionPropertiesUpdate");
  635. writer.Write(SerializeSessionPropertiesBinary());
  636. SendToAll(writer, SendDataOptions.Reliable);
  637. }
  638. private void ProcessIncomingMessages()
  639. {
  640. foreach (var gamer in gamers)
  641. {
  642. while (gamer.IsDataAvailable)
  643. {
  644. var reader = new PacketReader();
  645. gamer.ReceiveData(reader, out var sender);
  646. var messageType = reader.ReadString();
  647. if (messageType == "SessionPropertiesUpdate")
  648. {
  649. var propertiesData = reader.ReadBytes();
  650. DeserializeSessionPropertiesBinary(propertiesData);
  651. }
  652. }
  653. }
  654. }
  655. private void NotifyPendingGamers()
  656. {
  657. if (isGamerJoinedSubscribed && sessionState == NetworkSessionState.Lobby)
  658. {
  659. // Notify all pending gamers that they can join
  660. foreach (var gamer in gamers/*.Where(g => !g.IsLocal && !g.IsReady)*/)
  661. {
  662. gamerJoined?.Invoke(this, new GamerJoinedEventArgs(gamer));
  663. }
  664. }
  665. }
  666. }
  667. }