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