NetworkSessionComponent.cs 14 KB

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