NetworkSessionComponent.cs 15 KB

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