NetworkSessionComponent.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //-----------------------------------------------------------------------------
  2. // NetworkSessionComponent.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Linq;
  9. using System.Diagnostics;
  10. using System.Collections.Generic;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Net;
  13. using Microsoft.Xna.Framework.GamerServices;
  14. namespace NetworkStateManagement
  15. {
  16. /// <summary>
  17. /// Component in charge of owning and updating the current NetworkSession object.
  18. /// This is responsible for calling NetworkSession.Update at regular intervals,
  19. /// and also exposes the NetworkSession as a game service which can easily be
  20. /// looked up by any other code that needs to access it.
  21. /// </summary>
  22. class NetworkSessionComponent : GameComponent
  23. {
  24. public const int MaxGamers = 16;
  25. public const int MaxLocalGamers = 4;
  26. ScreenManager screenManager;
  27. NetworkSession networkSession;
  28. IMessageDisplay messageDisplay;
  29. bool notifyWhenPlayersJoinOrLeave;
  30. string sessionEndMessage;
  31. /// <summary>
  32. /// The constructor is private: external callers should use the Create method.
  33. /// </summary>
  34. NetworkSessionComponent(ScreenManager screenManager,
  35. NetworkSession networkSession)
  36. : base(screenManager.Game)
  37. {
  38. this.screenManager = screenManager;
  39. this.networkSession = networkSession;
  40. // Hook up our session event handlers.
  41. networkSession.GamerJoined += GamerJoined;
  42. networkSession.GamerLeft += GamerLeft;
  43. networkSession.SessionEnded += NetworkSessionEnded;
  44. }
  45. /// <summary>
  46. /// Creates a new NetworkSessionComponent.
  47. /// </summary>
  48. public static void Create(ScreenManager screenManager,
  49. NetworkSession networkSession)
  50. {
  51. Game game = screenManager.Game;
  52. // Register this network session as a service.
  53. game.Services.AddService(typeof(NetworkSession), networkSession);
  54. // Create a NetworkSessionComponent, and add it to the Game.
  55. game.Components.Add(new NetworkSessionComponent(screenManager,
  56. networkSession));
  57. }
  58. /// <summary>
  59. /// Initializes the component.
  60. /// </summary>
  61. public override void Initialize()
  62. {
  63. base.Initialize();
  64. // Look up the IMessageDisplay service, which will
  65. // be used to report gamer join/leave notifications.
  66. messageDisplay = (IMessageDisplay)Game.Services.GetService(
  67. typeof(IMessageDisplay));
  68. if (messageDisplay != null)
  69. notifyWhenPlayersJoinOrLeave = true;
  70. }
  71. /// <summary>
  72. /// Shuts down the component.
  73. /// </summary>
  74. protected override void Dispose(bool disposing)
  75. {
  76. if (disposing)
  77. {
  78. // Remove the NetworkSessionComponent.
  79. Game.Components.Remove(this);
  80. // Remove the NetworkSession service.
  81. Game.Services.RemoveService(typeof(NetworkSession));
  82. // Dispose the NetworkSession.
  83. if (networkSession != null)
  84. {
  85. networkSession.Dispose();
  86. networkSession = null;
  87. }
  88. }
  89. base.Dispose(disposing);
  90. }
  91. /// <summary>
  92. /// Updates the network session.
  93. /// </summary>
  94. public override void Update(GameTime gameTime)
  95. {
  96. if (networkSession == null)
  97. return;
  98. try
  99. {
  100. networkSession.Update();
  101. // Has the session ended?
  102. if (networkSession.SessionState == NetworkSessionState.Ended)
  103. {
  104. LeaveSession();
  105. }
  106. }
  107. catch (Exception exception)
  108. {
  109. // Handle any errors from the network session update.
  110. Debug.WriteLine("NetworkSession.Update threw " + exception);
  111. sessionEndMessage = Resources.ErrorNetwork;
  112. LeaveSession();
  113. }
  114. }
  115. /// <summary>
  116. /// Event handler called when a gamer joins the session.
  117. /// Displays a notification message.
  118. /// </summary>
  119. void GamerJoined(object sender, GamerJoinedEventArgs e)
  120. {
  121. if (notifyWhenPlayersJoinOrLeave)
  122. {
  123. messageDisplay.ShowMessage(Resources.MessageGamerJoined,
  124. e.Gamer.Gamertag);
  125. }
  126. }
  127. /// <summary>
  128. /// Event handler called when a gamer leaves the session.
  129. /// Displays a notification message.
  130. /// </summary>
  131. void GamerLeft(object sender, GamerLeftEventArgs e)
  132. {
  133. if (notifyWhenPlayersJoinOrLeave)
  134. {
  135. messageDisplay.ShowMessage(Resources.MessageGamerLeft,
  136. e.Gamer.Gamertag);
  137. }
  138. }
  139. /// <summary>
  140. /// Event handler called when the network session ends.
  141. /// Stores the end reason, so this can later be displayed to the user.
  142. /// </summary>
  143. void NetworkSessionEnded(object sender, NetworkSessionEndedEventArgs e)
  144. {
  145. switch (e.EndReason)
  146. {
  147. case NetworkSessionEndReason.ClientSignedOut:
  148. sessionEndMessage = null;
  149. break;
  150. case NetworkSessionEndReason.HostEndedSession:
  151. sessionEndMessage = Resources.ErrorHostEndedSession;
  152. break;
  153. // TODO: Check if the compatibility layer supports RemovedByHost
  154. // case NetworkSessionEndReason.RemovedByHost:
  155. // sessionEndMessage = Resources.ErrorRemovedByHost;
  156. // break;
  157. case NetworkSessionEndReason.Disconnected:
  158. default:
  159. sessionEndMessage = Resources.ErrorDisconnected;
  160. break;
  161. }
  162. notifyWhenPlayersJoinOrLeave = false;
  163. }
  164. /// <summary>
  165. /// Event handler called when the system delivers an invite notification.
  166. /// This can occur when the user accepts an invite that was sent to them by
  167. /// a friend (pull mode), or if they choose the "Join Session In Progress"
  168. /// option in their friends screen (push mode). The handler leaves the
  169. /// current session (if any), then joins the session referred to by the
  170. /// invite. It is not necessary to prompt the user before doing this, as
  171. /// the Guide will already have taken care of the necessary confirmations
  172. /// before the invite was delivered to you.
  173. /// </summary>
  174. public static void InviteAccepted(ScreenManager screenManager,
  175. InviteAcceptedEventArgs e)
  176. {
  177. // If we are already in a network session, leave it now.
  178. NetworkSessionComponent self = FindSessionComponent(screenManager.Game);
  179. if (self != null)
  180. self.Dispose(true);
  181. try
  182. {
  183. // Which local profiles should we include in this session?
  184. PlayerIndex defaultPlayerIndex = PlayerIndex.One;
  185. IEnumerable<SignedInGamer> localGamers =
  186. ChooseGamers(NetworkSessionType.PlayerMatch, defaultPlayerIndex);
  187. // Begin an asynchronous join-from-invite operation using the modern API.
  188. var joinTask = NetworkSession.JoinInvitedAsync(
  189. localGamers,
  190. null);
  191. // Use the loading screen to replace whatever screens were previously
  192. // active. This will completely reset the screen state, regardless of
  193. // whether we were in the menus or playing a game when the invite was
  194. // delivered. When the loading screen finishes, it will activate the
  195. // network busy screen, which displays an animation as it waits for
  196. // the join operation to complete.
  197. NetworkBusyScreen busyScreen = new NetworkBusyScreen(joinTask);
  198. busyScreen.OperationCompleted += JoinInvitedOperationCompleted;
  199. LoadingScreen.Load(screenManager, false, null, new BackgroundScreen(),
  200. busyScreen);
  201. }
  202. catch (Exception exception)
  203. {
  204. NetworkErrorScreen errorScreen = new NetworkErrorScreen(exception);
  205. LoadingScreen.Load(screenManager, false, null, new BackgroundScreen(),
  206. new MainMenuScreen(),
  207. errorScreen);
  208. }
  209. }
  210. /// <summary>
  211. /// Event handler for when the asynchronous join-from-invite
  212. /// operation has completed.
  213. /// </summary>
  214. static void JoinInvitedOperationCompleted(object sender,
  215. OperationCompletedEventArgs e)
  216. {
  217. ScreenManager screenManager = ((GameScreen)sender).ScreenManager;
  218. try
  219. {
  220. // Use the result directly from the event args.
  221. NetworkSession networkSession = e.Result as NetworkSession;
  222. if (networkSession == null)
  223. throw new InvalidOperationException("NetworkSession result was null or invalid.");
  224. // Create a component that will manage the session we just created.
  225. NetworkSessionComponent.Create(screenManager, networkSession);
  226. // Go to the lobby screen.
  227. screenManager.AddScreen(new LobbyScreen(networkSession), null);
  228. }
  229. catch (Exception exception)
  230. {
  231. screenManager.AddScreen(new MainMenuScreen(), null);
  232. screenManager.AddScreen(new NetworkErrorScreen(exception), null);
  233. }
  234. }
  235. /// <summary>
  236. /// Checks whether the specified session type is online.
  237. /// Online sessions cannot be used by local profiles, or if
  238. /// parental controls are enabled, or when running in trial mode.
  239. /// </summary>
  240. public static bool IsOnlineSessionType(NetworkSessionType sessionType)
  241. {
  242. switch (sessionType)
  243. {
  244. case NetworkSessionType.Local:
  245. case NetworkSessionType.SystemLink:
  246. return false;
  247. case NetworkSessionType.PlayerMatch:
  248. //case NetworkSessionType.Ranked:
  249. return true;
  250. default:
  251. throw new NotSupportedException();
  252. }
  253. }
  254. /// <summary>
  255. /// Decides which local gamer profiles should be included in a network session.
  256. /// This is passed the index of the primary gamer (the profile who selected the
  257. /// relevant menu option, or who is responding to an invite). The primary gamer
  258. /// will always be included in the session. Other gamers may also be added if
  259. /// there are suitable profiles signed in. To control how many gamers can be
  260. /// returned by this method, adjust the MaxLocalGamers constant.
  261. /// </summary>
  262. public static IEnumerable<SignedInGamer> ChooseGamers(
  263. NetworkSessionType sessionType,
  264. PlayerIndex playerIndex)
  265. {
  266. List<SignedInGamer> gamers = new List<SignedInGamer>();
  267. // Look up the primary gamer, and make sure they are signed in.
  268. SignedInGamer primaryGamer = Gamer.SignedInGamers[(int)playerIndex];
  269. if (primaryGamer == null)
  270. throw new GamerPrivilegeException();
  271. gamers.Add(primaryGamer);
  272. // Check whether any other profiles should also be included.
  273. foreach (SignedInGamer gamer in Gamer.SignedInGamers)
  274. {
  275. // Never include more profiles than the MaxLocalGamers constant.
  276. if (gamers.Count >= MaxLocalGamers)
  277. break;
  278. // Don't want two copies of the primary gamer!
  279. if (gamer == primaryGamer)
  280. continue;
  281. // If this is an online session, make sure the profile is signed
  282. // in to Live, and that it has the privilege for online gameplay.
  283. if (IsOnlineSessionType(sessionType))
  284. {
  285. if (!gamer.IsSignedInToLive)
  286. continue;
  287. // TODO: Check if the compatibility layer supports Privileges
  288. // For now, assume online privileges are available if signed in to Live
  289. // if (!gamer.Privileges.AllowOnlineSessions)
  290. // continue;
  291. }
  292. if (primaryGamer.IsGuest && !gamer.IsGuest && gamers[0] == primaryGamer)
  293. {
  294. // Special case: if the primary gamer is a guest profile,
  295. // we should insert some other non-guest at the start of the
  296. // output list, because guests aren't allowed to host sessions.
  297. gamers.Insert(0, gamer);
  298. }
  299. else
  300. {
  301. gamers.Add(gamer);
  302. }
  303. }
  304. return gamers;
  305. }
  306. /// <summary>
  307. /// Public method called when the user wants to leave the network session.
  308. /// Displays a confirmation message box, then disposes the session, removes
  309. /// the NetworkSessionComponent, and returns them to the main menu screen.
  310. /// </summary>
  311. public static void LeaveSession(ScreenManager screenManager,
  312. PlayerIndex playerIndex)
  313. {
  314. NetworkSessionComponent self = FindSessionComponent(screenManager.Game);
  315. if (self != null)
  316. {
  317. // Display a message box to confirm the user really wants to leave.
  318. string message;
  319. if (self.networkSession.IsHost)
  320. message = Resources.ConfirmEndSession;
  321. else
  322. message = Resources.ConfirmLeaveSession;
  323. MessageBoxScreen confirmMessageBox = new MessageBoxScreen(message);
  324. // Hook the messge box ok event to actually leave the session.
  325. confirmMessageBox.Accepted += delegate
  326. {
  327. self.LeaveSession();
  328. };
  329. screenManager.AddScreen(confirmMessageBox, playerIndex);
  330. }
  331. }
  332. /// <summary>
  333. /// Internal method for leaving the network session. This disposes the
  334. /// session, removes the NetworkSessionComponent, and returns the user
  335. /// to the main menu screen.
  336. /// </summary>
  337. void LeaveSession()
  338. {
  339. // Destroy this NetworkSessionComponent.
  340. Dispose(true);
  341. // If we have a sessionEndMessage string explaining why the session has
  342. // ended (maybe this was a network disconnect, or perhaps the host kicked
  343. // us out?) create a message box to display this reason to the user.
  344. MessageBoxScreen messageBox;
  345. if (!string.IsNullOrEmpty(sessionEndMessage))
  346. messageBox = new MessageBoxScreen(sessionEndMessage, false);
  347. else
  348. messageBox = null;
  349. // At this point we want to return the user all the way to the main
  350. // menu screen. But what if they just joined a session? In that case
  351. // they went through this flow of screens:
  352. //
  353. // - MainMenuScreen
  354. // - CreateOrFindSessionsScreen
  355. // - JoinSessionScreen (if joining, skipped if creating a new session)
  356. // - LobbyScreeen
  357. //
  358. // If we have these previous screens on the history stack, and the user
  359. // backs out of the LobbyScreen, the right thing is just to pop off the
  360. // intermediate screens, returning them to the existing MainMenuScreen
  361. // instance without bothering to reload everything. But if the user is
  362. // in gameplay, or has been in gameplay and then returned to the lobby,
  363. // the screen stack will have been emptied.
  364. //
  365. // To do the right thing in both cases, we scan through the screen history
  366. // stack looking for a MainMenuScreen. If we find one, we pop any
  367. // subsequent screens so as to return back to it, while if we don't
  368. // find it, we just reset everything via the LoadingScreen.
  369. GameScreen[] screens = screenManager.GetScreens();
  370. // Look for the MainMenuScreen.
  371. for (int i = 0; i < screens.Length; i++)
  372. {
  373. if (screens[i] is MainMenuScreen)
  374. {
  375. // If we found one, pop everything since then to return back to it.
  376. for (int j = i + 1; j < screens.Length; j++)
  377. screens[j].ExitScreen();
  378. // Display the why-did-the-session-end message box.
  379. if (messageBox != null)
  380. screenManager.AddScreen(messageBox, null);
  381. return;
  382. }
  383. }
  384. // If we didn't find an existing MainMenuScreen, reload everything.
  385. // The why-did-the-session-end message box will be displayed after
  386. // the loading screen has completed.
  387. LoadingScreen.Load(screenManager, false, null, new BackgroundScreen(),
  388. new MainMenuScreen(),
  389. messageBox);
  390. }
  391. /// <summary>
  392. /// Searches through the Game.Components collection to
  393. /// find the NetworkSessionComponent (if any exists).
  394. /// </summary>
  395. static NetworkSessionComponent FindSessionComponent(Game game)
  396. {
  397. return game.Components.OfType<NetworkSessionComponent>().FirstOrDefault();
  398. }
  399. }
  400. }