Receiving Network Data

Describes how local players on a gaming machine receive data from the other players in a networked game.

The Complete Sample

The code in the topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Download NetworkingSample.

Receiving Data

To receive data

  1. Create a PacketReader to assist in reading incoming network data.

    A PacketReader is a helper for efficiently reading incoming network packets. A multiplayer game can create a single PacketReader instance at startup and can reuse it any time the players want to read a packet.

    PacketReader packetReader = new PacketReader();
    

    Each LocalNetworkGamer playing on the same game machine might receive data. At this point, players can loop through the LocalGamers collection.

  2. Pass the PacketReader to ReceiveData, and then use the various PacketReader.Read methods to extract data from the reader.

    foreach (LocalNetworkGamer gamer in session.LocalGamers)
    {
        // Keep reading while packets are available.
        while (gamer.IsDataAvailable)
        {
            NetworkGamer sender;
    
            // Read a single packet.
            gamer.ReceiveData(packetReader, out sender);
    
            if (!sender.IsLocal)
            {
                // Get the tank associated with this packet.
                Tank remoteTank = sender.Tag as Tank;
    
                // Read the data and apply it to the tank.
                remoteTank.Position = packetReader.ReadVector2();
                remoteTank.TankRotation = packetReader.ReadSingle();
                remoteTank.TurretRotation = packetReader.ReadSingle();
                remoteTank.IsFiring = packetReader.ReadBoolean();
                remoteTank.Health = packetReader.ReadInt32();
            }
        }
    }
    

See Also

Tasks

Setting up your Firewall