Joining and Leaving a Game

Manage data associated with a player by subscribing to events that occur when players join or leave a game.

A NetworkSession contains several properties that list the players who have joined a session. The collection of all gamers in a session is described by the NetworkSession.AllGamers property. This information is guaranteed to be the same on each game machines in a session. Within this list, the gamers might be local (playing on the same game machine through split-screen play) or remote (playing on a different game machine). The property NetworkSession.LocalGamers provides a list of all local players playing on a local game machine. The NetworkSession.RemoteGamers property provides a list of all players not playing on the local game machine.

To respond to players joining or leaving the game, you may subscribe to the NetworkSession.GamerJoined and NetworkSession.GamerLeft events and create custom event handlers. When a new event handler is attached to NetworkSession.GamerJoined the handler receives join notifications for all players currently in the session. This means there will be a join notification for each gamer that has joined the session before the event handler is attached to the event.

Subscribing to Gamer Events

To subscribe to gamer events

  1. After creating or joining a session, subscribe to events associated with players joining or leaving the game.

    session.GamerJoined += 
        new EventHandler<GamerJoinedEventArgs>(session_GamerJoined);
    session.GamerLeft += 
        new EventHandler<GamerLeftEventArgs>(session_GamerLeft);
    
  2. Create the GamerJoined event handler.

    void session_GamerJoined(object sender, GamerJoinedEventArgs e)
    {
        // Associate a tank object with this gamer.
        e.Gamer.Tag = 
            new Tank(Content, GraphicsDevice.PresentationParameters);
    
    }
    

    Note

    The GamerJoinedEventArgs object contains a Gamer property. You can use it to read information about, or to associate information with, a specific player. Use the Gamer.Tag property to associate data with a player.

  3. Create the GamerLeft event handler.

    void session_GamerLeft(object sender, GamerLeftEventArgs e)
    {
        Tank tank = e.Gamer.Tag as Tank;
    
        tank.LeaveGame();
    }
    

Note

If the host player leaves the session calling Game.Exit, this forces a host reelection. The host is automatically migrated to another player. If you use a client-server or hybrid network topology instead of a peer-to-peer, and if your host also is a server in the game, it is necessary to migrate game state to the new game server when the host is migrated. Players in the game can use the HostChanged event to respond to host migration.

See Also

Concepts

Network Session Management

Tasks

Creating a Network Session
Finding and Joining a Network Session