Skip to content

Networking

JonataOliveiraa edited this page Nov 14, 2026 · 1 revision
Intermediate

In multiplayer every player's game runs on their own device, and the server keeps them in agreement. Most of what the game does is synced for you, but data that only your mod knows about is not: for that, your mod sends its own messages with ModPacket. This page shows how, and how an item can carry its data across the network.

Multiplayer: ModPacket

A mod talks to itself on the other side of the connection with packets, as in tModLoader:

// send (a client sends to the server; the server to one client or to all)
ModPacket packet = Mod.GetPacket();
packet.Write((byte)MyMessage.Heal);
packet.Write(Main.myPlayer);
packet.Write(50);
packet.Send();                 // the server: Send(toClient, ignoreClient)

// receive, in your Mod class
public override void HandlePacket(BinaryReader reader, int whoAmI)
{
    switch ((MyMessage)reader.ReadByte())
    {
        case MyMessage.Heal:
            int player = reader.ReadInt32();
            int amount = reader.ReadInt32();
            // ...
            break;
    }
}
  • ModPacket is a BinaryWriter: Write takes numbers, bool, string, byte[]. HandlePacket gets a BinaryReader positioned at what you wrote: read in the same order.
  • whoAmI is the sender: on the server, the client's player index; on a client, 256 (the server).
  • Send() in single player throws. A packet holds at most 65,000 bytes.
  • A packet for a mod that the other side does not have is dropped, with a line in the log.

Joining a server. When a client joins, it tells the server which C# mods it has (name and version). A client whose C# mods are not the same as the server's is refused, with a message that lists the server's mods, the ones the client is missing and the ones only the client has. With Mod sync on in the host's settings, the client is offered the server's mods to download (Joining a server).

An item's data on the network

The game sends an item when it changes hands: a player's slot (message 5), an item on the ground (21 and 90), a chest slot (32). The data of a ModItem goes with it:

public class Charged : ModItem
{
    public int Charge;

    public override void NetSend(BinaryWriter writer) => writer.Write(Charge);

    public override void NetReceive(BinaryReader reader) => Charge = reader.ReadInt32();
}

GlobalItem has the same two, with the Item first (InstancePerEntity for per-item fields), for any item. A ModItem without NetSend that has SaveData sends what SaveData writes instead, and the other side runs LoadData with it, so a saved field also reaches the server (which saves the chests) and the other players. Write and read the same things, in the same order. The data goes as a C# packet just before the game's message, and is applied right after the game reads it; on a server, before the game passes the message on to the other players.


← Touch buttons  ·  Cross-mod content →

Clone this wiki locally