2
0

NetworkSessionComponent.cs 14 KB

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