Sending Network Data

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

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.

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 can reuse it any time 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. Call the various overloads of the PacketWriter.Write method to store data into the writer, and then pass the PacketWriter to SendData.

    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);


    Sending a packet automatically clears the PacketWriter. The sent packet can 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. Data can be sent to a specific player by identifying the player in a call to SendData.

See Also


Setting up your Firewall