Monday, December 3, 2007

Networking Step 5: Searching for a LIVE Session

Unfortunately im unable to test this just yet (as I don't know anybody who has a beta key to host a game for me on LIVE) so I hope it works.

I'll keep it as simple as possible for now, so we are going to add another new screen to search for available sessions:

#region using
using System;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework;
#endregion

namespace GameStateManagement
{
class SearchScreen : MenuScreen
{
AvailableNetworkSessionCollection availableSessions;
int maxLocalPlayers = 2;

// Used for making the Searching Asynchronous.
IAsyncResult LIVESearch = null;

public SearchScreen()
{
NetworkSessionProperties searchProperties = new NetworkSessionProperties();

LIVESearch = NetworkSession.BeginFind(NetworkSessionType.PlayerMatch, maxLocalPlayers, searchProperties,
new AsyncCallback(SessionsFound), null);
}

/// <summary>
/// Responds to user menu selections.
/// </summary>
protected override void OnSelectEntry(int entryIndex)
{

}

/// <summary>
/// When the user cancels the options screen, go back to the main menu.
/// </summary>
protected override void OnCancel()
{
ExitScreen();
}

/// <summary>
/// Callback to receive the search results of the available LIVE Sessions
/// </summary>
public void SessionsFound(IAsyncResult result)
{
if ((LIVESearch != null) && LIVESearch.IsCompleted)
{
availableSessions = NetworkSession.EndFind(result);
MenuEntries.Clear();

if (availableSessions != null)
{
foreach (AvailableNetworkSession availableSession in availableSessions)
{
// Only show sessions where there are available slots
if (availableSession.CurrentGamerCount < 8)
{
MenuEntries.Add(availableSession.HostGamertag + " (" +
availableSession.CurrentGamerCount.ToString() + "/8)");
}

// Limit the number of results to return
if (MenuEntries.Count >= 5)
{
break;
}
}
}

LIVESearch = null;
}
}
}
}

Finally lets modify the XBoxLiveScreen.cs and add to case 1 in the OnSelectEntry function the following line:
ScreenManager.AddScreen(new SearchScreen());

And that's it for now, I'm going to move onto System Link next so that I can at least test what im writing.

No comments: