/// <summary> /// Event handler for when the asynchronous find network sessions /// operation has completed. /// </summary> void FindSessionsOperationCompleted(object sender, OperationCompletedEventArgs e) { GameScreen nextScreen; try { // End the asynchronous find network sessions operation. AvailableNetworkSessionCollection availableSessions = NetworkSession.EndFind(e.AsyncResult); if (availableSessions.Count == 0) { // If we didn't find any sessions, display an error. availableSessions.Dispose(); nextScreen = new MessageBoxScreen(Resources.NoSessionsFound, false); } else { // If we did find some sessions, proceed to the JoinSessionScreen. nextScreen = new JoinSessionScreen(availableSessions); } } catch (Exception exception) { nextScreen = new NetworkErrorScreen(exception); } ScreenManager.AddScreen(nextScreen, ControllingPlayer); }
/// <summary> /// Callback to receive the network-session search results from quick-match. /// </summary> void QuickMatchSearchCompleted(object sender, OperationCompletedEventArgs e) { try { AvailableNetworkSessionCollection availableSessions = NetworkSession.EndFind(e.AsyncResult); if ((availableSessions != null) && (availableSessions.Count > 0)) { // join the session try { IAsyncResult asyncResult = NetworkSession.BeginJoin( availableSessions[0], null, null); // create the busy screen NetworkBusyScreen busyScreen = new NetworkBusyScreen( "Joining the session...", asyncResult); busyScreen.OperationCompleted += QuickMatchSessionJoined; ScreenManager.AddScreen(busyScreen); } catch (NetworkException ne) { const string message = "Failed joining the session."; MessageBoxScreen messageBox = new MessageBoxScreen(message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); System.Console.WriteLine("Failed to join session: " + ne.Message); } catch (GamerPrivilegeException gpe) { const string message = "You do not have permission to join a session."; MessageBoxScreen messageBox = new MessageBoxScreen(message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); System.Console.WriteLine( "Insufficient privilege to join session: " + gpe.Message); } } else { const string message = "No matches were found."; MessageBoxScreen messageBox = new MessageBoxScreen(message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); } } catch (GamerPrivilegeException gpe) { MessageBoxScreen messageBox = new MessageBoxScreen(gpe.Message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); } }
private static void FindSessionsComplete(IAsyncResult result) { AvailableNetworkSessionCollection sessions = NetworkSession.EndFind(result); FindSessionCompleteHandler call = (FindSessionCompleteHandler)result.AsyncState; call.Invoke(sessions); }
/// <summary> /// Raised when a Live find query returns /// </summary> /// <param name="asyncResult"></param> private void OnLiveSessionsFound(IAsyncResult asyncResult) { var sessions = new List <AvailableSession>(); AvailableNetworkSessionCollection availableLiveSessions = NetworkSession.EndFind(asyncResult); foreach (AvailableNetworkSession availableLiveSession in availableLiveSessions) { sessions.Add(new LiveAvailableSession(availableLiveSession)); } OnSessionsFound(sessions.AsReadOnly()); }
/* Completion of looking for sessions. */ protected virtual void OnSessionsFound(IAsyncResult ar) { findAsync_ = null; AvailableNetworkSessionCollection availableSessions = NetworkSession.EndFind(ar); if (availableSessions.Count != 0) { /* Pick one of the available sessions. */ List <AvailableNetworkSession> toChooseFrom = new List <AvailableNetworkSession>(); Trace.WriteLine(String.Format("Found {0} potential network sessions.", availableSessions.Count)); foreach (AvailableNetworkSession ans in availableSessions) { if (ans.OpenPublicGamerSlots < saveLocalPlayerCount && ans.OpenPublicGamerSlots < SignedInGamer.SignedInGamers.Count) { // full continue; } if (sessionType != SessionType.HighscoresOnly || !previousSessionHosts.Member(ans.HostGamertag)) { // this seems like an OK session, use that! toChooseFrom.Add(ans); } } if (toChooseFrom.Count > 0) { // pick one at random AvailableNetworkSession ans = toChooseFrom[rand.Next(toChooseFrom.Count)]; previousSessionHosts.Add(ans.HostGamertag); Trace.WriteLine(String.Format("Connecting to session hosted by '{0}'", ans.HostGamertag)); ConnectToSession(ans); return; } else { /* I went through all the possible sessions, so now I can re-start looking * at hosts I've previously talked to. */ previousSessionHosts.Clear(); } } // OK, nothing matched -- try to create something for others to find Trace.WriteLine("Creating session because no available session was suitable."); Debug.Assert(createAsync_ == null); createAsync_ = NetworkSession.BeginCreate(netType, saveLocalPlayerCount, saveTotalPlayerCount, 0, saveProps, OnSessionCreated, null); Debug.Assert(createAsync_.CompletedSynchronously == false); }
/// <summary> /// Callback to receive the network-session search results. /// </summary> internal void SessionsFound(object sender, OperationCompletedEventArgs e) { try { availableSessions = NetworkSession.EndFind(e.AsyncResult); } catch (NetworkException ne) { const string message = "Failed searching for the session."; MessageBoxScreen messageBox = new MessageBoxScreen(message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); System.Console.WriteLine("Failed to search for session: " + ne.Message); } catch (GamerPrivilegeException gpe) { const string message = "You do not have permission to search for a session. "; MessageBoxScreen messageBox = new MessageBoxScreen(message + gpe.Message); messageBox.Accepted += FailedMessageBox; messageBox.Cancelled += FailedMessageBox; ScreenManager.AddScreen(messageBox); System.Console.WriteLine( "Insufficient privilege to search for session: " + gpe.Message); } MenuEntries.Clear(); if (availableSessions != null) { foreach (AvailableNetworkSession availableSession in availableSessions) { if (availableSession.CurrentGamerCount < World.MaximumPlayers) { MenuEntries.Add(availableSession.HostGamertag + " (" + availableSession.CurrentGamerCount.ToString() + "/" + World.MaximumPlayers.ToString() + ")"); } if (MenuEntries.Count >= maximumSessions) { break; } } } }
public void session_SessionFound(IAsyncResult result) { // All sessions found AvailableNetworkSessionCollection availableSessions; // The session we will join AvailableNetworkSession availableSession = null; if (AsyncSessionFind.IsCompleted) { Console.WriteLine("AsyncSessionFind.IsCompleted"); availableSessions = NetworkSession.EndFind(result); // Look for a session with available gamer slots foreach (AvailableNetworkSession curSession in availableSessions) { Console.WriteLine("foreach"); int TotalSessionSlots = curSession.OpenPublicGamerSlots + curSession.OpenPrivateGamerSlots; if (TotalSessionSlots > curSession.CurrentGamerCount) { Console.WriteLine("TotalSessionSlots"); availableSession = curSession; } } // If a session was found, connect to it if (availableSession != null) { message = "Found an available session at host " + availableSession.HostGamertag; session = NetworkSession.Join(availableSession); } else { message = "No sessions found."; } // Reset the session finding result AsyncSessionFind = null; } }
private void EndAsynchSearch(IAsyncResult result) { AvailableNetworkSessionCollection activeSessions = NetworkSession.EndFind(result); if (activeSessions.Count == 0) { currentGameState = GameState.CreateSession; log.Add("No active sessions found - proceed to CreateSession"); } else { AvailableNetworkSession sessionToJoin = activeSessions[0]; networkSession = NetworkSession.Join(sessionToJoin); string myString = "Joined session hosted by " + sessionToJoin.HostGamertag; myString += " with " + sessionToJoin.CurrentGamerCount.ToString() + " players"; myString += " and " + sessionToJoin.OpenPublicGamerSlots.ToString() + " open player slots."; log.Add(myString); HookSessionEvents(); currentGameState = GameState.InSession; } }
public virtual void session_SessionFound(IAsyncResult result) { // all sessions found AvailableNetworkSessionCollection availableSessions; // the session we will join AvailableNetworkSession availableSession = null; if (AsyncSessionFind.IsCompleted) { availableSessions = NetworkSession.EndFind(result); // Look for a session with available gamer slots foreach (AvailableNetworkSession curSession in availableSessions) { int TotalSessionSlots = curSession.OpenPublicGamerSlots + curSession.OpenPrivateGamerSlots; if (TotalSessionSlots > curSession.CurrentGamerCount) { availableSession = curSession; } } // if a session was found, connect to it if (availableSession != null) { sayMessage("Found an available session at host" + availableSession.HostGamertag); Session = NetworkSession.Join(availableSession); } else { sayMessage("No sessions found!"); } // Reset the session finding result AsyncSessionFind = null; } }
private void NetSessionsFound(IAsyncResult res) { _asyncSessionOperationsInProgress--; if (SessionsFound != null) { NetworkSessionsFoundEventArgs eventArgs = new NetworkSessionsFoundEventArgs(); try { eventArgs.AvailableSessions = NetworkSession.EndFind(res); } catch (Exception ex) { eventArgs.Error = ex; } SessionsFound(this, eventArgs); if (eventArgs.SessionToJoin != null) { JoinSession(eventArgs.SessionToJoin); } } }
public void CheckNetworkSearch() { if (IsCreating || IsJoining || IsSearching) { bool TemparyProfiles = false; foreach (CompletePlayer player in game.ThisGamesPlayers) { if (player.InUse && !player.IsProfile) { TemparyProfiles = true; } } if (!TemparyProfiles) //if(true) { if (IsSearching && FindResult.IsCompleted) { FindResult.AsyncWaitHandle.WaitOne(); try { availableSessions = NetworkSession.EndFind(FindResult); if (availableSessions.Count == 0) { SetString("No Games Found, Creating Game..."); CreateGame(); } else { SetString(availableSessions.Count.ToString() + " Games Found\nFinding Best Game"); SortSessions(); } IsSearching = false; } catch (Exception e) { // if(networkSession==null) if (e.Message != null) { OnlineString = " "; game.ErrorMessage = e.Message.Replace(". ", ".\n"); game.menus.GoTo("Error", false); IsCreating = false; IsJoining = false; IsSearching = false; } } IsSearching = false; } if (IsJoining && JoinResult.IsCompleted) { JoinResult.AsyncWaitHandle.WaitOne(); try { networkSession = NetworkSession.EndJoin(JoinResult); HookSessionEvents(); BeginOnlineGameAsGuest(); } catch (Exception e) { // if (networkSession == null) if (e.Message != null) { OnlineString = " "; game.ErrorMessage = e.Message.Replace(". ", ".\n"); game.menus.GoTo("Error", false); IsCreating = false; IsJoining = false; IsSearching = false; } } IsJoining = false; } if (IsCreating && CreateResult.IsCompleted) { CreateResult.AsyncWaitHandle.WaitOne(); try { networkSession = NetworkSession.EndCreate(CreateResult); HookSessionEvents(); BeginOnlineGameAsHost(); } catch (Exception e) { if (e.Message != null) { OnlineString = " "; game.ErrorMessage = e.Message.Replace(". ", ".\n"); game.menus.GoTo("Error", false); IsCreating = false; IsJoining = false; IsSearching = false; } } IsCreating = false; } } else { OnlineString = " "; game.ErrorMessage = "No Temporary Profiles May Be Taken Online \n Sign into XBOX LIVE Guest Profiles Instead"; game.menus.GoTo("Error", false); IsCreating = false; IsJoining = false; IsSearching = false; } } }
/// <summary> /// Update /// </summary> public override void Update(GameTime gameTime) { // Process different phases. switch (phase) { case ConnectionPahse.EnsureSignedIn: GamerServicesDispatcher.Update(); break; case ConnectionPahse.FindSessions: GamerServicesDispatcher.Update(); if (asyncResult.IsCompleted) { AvailableNetworkSessionCollection sessions = NetworkSession.EndFind(asyncResult); if (sessions.Count > 0) { asyncResult = NetworkSession.BeginJoin(sessions[0], null, null); commandHost.EchoError("Connecting to the host..."); phase = ConnectionPahse.Joining; } else { commandHost.EchoError("Couldn't find a session."); phase = ConnectionPahse.None; } } break; case ConnectionPahse.Joining: GamerServicesDispatcher.Update(); if (asyncResult.IsCompleted) { NetworkSession = NetworkSession.EndJoin(asyncResult); NetworkSession.SessionEnded += new EventHandler <NetworkSessionEndedEventArgs>( NetworkSession_SessionEnded); OwnsNetworkSession = true; commandHost.EchoError("Connected to the host."); phase = ConnectionPahse.None; asyncResult = null; ConnectedToRemote(); } break; } // Update Network session. if (OwnsNetworkSession) { GamerServicesDispatcher.Update(); NetworkSession.Update(); if (NetworkSession != null) { // Process received packets. foreach (LocalNetworkGamer gamer in NetworkSession.LocalGamers) { while (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(packetReader, out sender); if (!sender.IsLocal) { ProcessRecievedPacket(packetReader.ReadString()); } } } } } base.Update(gameTime); }
public void Update() { if (PendingHost) { if (createResult.IsCompleted) { netPlay.NetSession = NetworkSession.EndCreate(createResult); netPlay.Hosting = true; PendingHost = false; } } if (PendingFind) { if (findResult.IsCompleted) { AvailableNetworkSessionCollection availableSessions = NetworkSession.EndFind(findResult); if (availableSessions.Count > 0) { joinResult = NetworkSession.BeginJoin( availableSessions[0], new AsyncCallback(GotResult), null); PendingJoin = true; } PendingFind = false; } } if (PendingJoin) { if (joinResult.IsCompleted) { netPlay.NetSession = NetworkSession.EndJoin(joinResult); netPlay.Joined = true; PendingJoin = false; } } if (netPlay.Hosting) { // } if (netPlay.Joined) { // } if (netPlay.NetSession != null) { if (!netPlay.NetSession.IsDisposed) { bool ended = false; if (netPlay.NetSession.SessionState == NetworkSessionState.Playing) { if (netPlay.NetSession.AllGamers.Count < 2) { ended = true; } } else if (netPlay.NetSession.SessionState == NetworkSessionState.Ended) { ended = true; } if (ended) { Game1.Menu.EndGame(); netPlay.NetSession.Dispose(); netPlay.Hosting = false; netPlay.Joined = false; } } } }
void DisposeSession() { if (session != null) { Trace.WriteLine(String.Format("Disposing session: sessionCloseTime {0} now {1}", new DateTime(sessionCloseTime), DateTime.Now)); session.Dispose(); session = null; sessionDisconnected = true; } sessionCloseTime = 0; IDisposable id = null; /* If I'm currently looking for sessions to join, stop that. */ if (findAsync_ != null) { try { id = NetworkSession.EndFind(findAsync_); } catch (System.Exception x) { Trace.WriteLine("Swallowing EndFind exception: " + x.ToString()); } findAsync_ = null; if (id != null) { id.Dispose(); } } /* If I'mcurrently looking to join a session, stop that. */ if (joinAsync_ != null) { try { id = NetworkSession.EndJoin(joinAsync_); } catch (System.Exception x) { Trace.WriteLine("Swallowing EndJoin exception: " + x.ToString()); } joinAsync_ = null; if (id != null) { id.Dispose(); } } /* If I'm currently trying to host a session, stop that. */ if (createAsync_ != null) { try { id = NetworkSession.EndCreate(createAsync_); } catch (System.Exception x) { Trace.WriteLine("Swallowing EndCreate exception: " + x.ToString()); } createAsync_ = null; if (id != null) { id.Dispose(); } } }