NetworkSessionComponent.cs 19 KB

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