How To: Receive Data

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

Receiving Data

To receive data

  1. Create a PacketReader to assist in reading the 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. It 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. To read a packet, 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();

Community Additions