How To: Send Data

Describes the options available for sending data to all clients or to a specific player.

Sending Data

To send data to all peers

  1. Create a PacketWriter to use in writing the data.

    The PacketWriter is a helper for efficiently formatting outgoing network packets. A multiplayer game can create a single PacketWriter instance at startup, and reuse it any time the players want to send a packet.

    PacketWriter packetWriter = new PacketWriter();

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

  2. To send a packet, call the various overloads of the PacketWriter.Write method to store data into the writer, and then pass the PacketWriter to SendData.

    Note that it is also possible to send data to a specific player by specifying the player in the call to SendData.

    Sending the packet will automatically clear the PacketWriter. It can then be reused to write different data for another packet. Although it is not used in this example, the PacketWriter supports offsets through the Position property.

    In the call to SendData, be careful to specify a SendDataOptions value for options that is appropriate for the type of data being sent. Not all game data needs to be sent reliably. Sending excessive data using SendDataOptions.ReliableInOrder can cause the client to lag as it waits for data to be delivered in order.

    foreach (LocalNetworkGamer gamer in session.LocalGamers)
        // Get the tank associated with this player.
        Tank myTank = gamer.Tag as Tank;
        // Write the data.
        // Send it to everyone.
        gamer.SendData(packetWriter, SendDataOptions.None);

Community Additions